__dir__

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jacek Generowicz

    __dir__

    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 ?
  • Peter Otten

    #2
    Re: __dir__

    Jacek Generowicz wrote:
    [color=blue]
    > 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 ?[/color]
    [color=blue][color=green][color=darkred]
    >>> class C:[/color][/color][/color]
    .... __members__ = ["Is this evil?", "So what"]
    ....[color=blue][color=green][color=darkred]
    >>> dir(C)[/color][/color][/color]
    ['__doc__', '__members__', '__module__'][color=blue][color=green][color=darkred]
    >>> dir(C())[/color][/color][/color]
    ['Is this evil?', 'So what', '__doc__', '__members__', '__module__'][color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

    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

    Comment

    • Jacek Generowicz

      #3
      Re: __dir__

      Peter Otten <__peter__@web. de> writes:
      [color=blue]
      > 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.[/color]

      Great, sounds just perfect for my needs ;-)

      Comment

      Working...