Improved python dir

May 29, 2011 at 7:48 pm Leave a comment

The results of dir are too long and writing comprehensions for filtering is slightly too painful. However there is a solution: replace it!

The following function is an improved version of dir that

* Pretty prints values
* Has an additional ‘filter’ argument that allows you to only search for names containing a particular string or matching a particular regular expression (this is case insensitive by default)


class PrettyList(list):
    def __repr__(self):
        return pprint.pformat(list(self))

UNSET = object()
def magic_dir(object=UNSET, filter='', flags=re.I):
    if object is UNSET:
        results = sys._getframe(1).f_locals.keys()
    else:
        results = dir(object)

    if isinstance(filter, str):
        regexp = re.compile(filter, flags)
    else:
        regexp = filter

    return PrettyList([x for x in results
        if regexp.search(x)])

I then smuggle this dir into my context replacing the builtin dir by setting PYTHONSTARTUP and doing the patching here. There are some slight issues with getting this into pdb, by it otherwise works wonderfully.

Advertisements

Entry filed under: Uncategorized. Tags: , , .

Mounting Android Devices at sane mount points Rule-based automation of gnucash transaction source detection

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


May 2011
M T W T F S S
« Apr   Jun »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

%d bloggers like this: