__dir__

Discussion in 'Python' started by Jacek Generowicz, May 13, 2004.

  1. Is there some way of affecting the way dir finds the information it presents?

    For example, supposing a hypothetical __dir__ magic method:

    class collection:
    def __init__(self, myname, names):
    self.names = names
    self.myname = myname
    def __dir__(self):
    return ['%s(%s)' % (self.myname,n) for n in self.names]

    class thingy:
    def __init__(self, *names):
    self.it = collection('it', names)

    thing = thingy('this', 'that', 'theother')

    dir(thing)

    ['__doc__', '__init__', '__module__', 'it(this)', 'it(that)', 'it(theother)']


    In other words, I would like some attributes of an instance to inject
    some information into the output of dir ... to change the way their
    names are perceived by dir.

    Any ideas ?
    Jacek Generowicz, May 13, 2004
    #1
    1. Advertising

  2. Jacek Generowicz

    Peter Otten Guest

    Jacek Generowicz wrote:

    > Is there some way of affecting the way dir finds the information it
    > presents?
    >
    > For example, supposing a hypothetical __dir__ magic method:
    >
    > class collection:
    > def __init__(self, myname, names):
    > self.names = names
    > self.myname = myname
    > def __dir__(self):
    > return ['%s(%s)' % (self.myname,n) for n in self.names]
    >
    > class thingy:
    > def __init__(self, *names):
    > self.it = collection('it', names)
    >
    > thing = thingy('this', 'that', 'theother')
    >
    > dir(thing)
    >
    > ['__doc__', '__init__', '__module__', 'it(this)', 'it(that)',
    > ['it(theother)']
    >
    >
    > In other words, I would like some attributes of an instance to inject
    > some information into the output of dir ... to change the way their
    > names are perceived by dir.
    >
    > Any ideas ?


    >>> class C:

    .... __members__ = ["Is this evil?", "So what"]
    ....
    >>> dir(C)

    ['__doc__', '__members__', '__module__']
    >>> dir(C())

    ['Is this evil?', 'So what', '__doc__', '__members__', '__module__']
    >>>


    However, __members__ is marked as deprecated and, even more important, I
    don't know what the side effects of the above may be.
    Highly unrecommended.

    Peter
    Peter Otten, May 13, 2004
    #2
    1. Advertising

  3. Peter Otten <> writes:

    > However, __members__ is marked as deprecated and, even more important, I
    > don't know what the side effects of the above may be.
    > Highly unrecommended.


    Great, sounds just perfect for my needs ;-)
    Jacek Generowicz, May 13, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page