Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #31800

Re: How to see the __name__ attribute of a class by using dir()

From Peter Otten <__peter__@web.de>
Subject Re: How to see the __name__ attribute of a class by using dir()
Date 2012-10-20 10:24 +0200
Organization None
References <k5tm0k$sph$1@speranza.aioe.org>
Newsgroups comp.lang.python
Message-ID <mailman.2554.1350721484.27098.python-list@python.org> (permalink)

Show all headers | View raw


Jennie wrote:

> The dir() built-in does not show the __name__ attribute of a class:
> 
>  >>> '__name__' in Foo.__dict__
> False
>  >>> Foo.__name__
> 'Foo'
> 
> I implementd my custom __dir__, but the dir() built-in do not want to
> call it:
> 
>  >>> class Foo:
> ...     @classmethod
> ...     def __dir__(cls):
> ...         return ['python']
> ...
>  >>> Foo.__dir__()
> ['python']
>  >>> dir(Foo)
> ['__class__', '__delattr__', '__dict__', ...]
> 
> Can someone tell me where is the problem? Thanks a lot in advance

Implementing __dir__ as an instance method works:

>>> class Foo(object):
...     def __dir__(self): return ["python"]
... 
>>> dir(Foo())
['python']

So if you want to customise dir(Foo) you have to modify the metaclass:

>>> class Foo:
...     class __metaclass__(type):
...             def __dir__(self): return ["python"]
... 
>>> dir(Foo)
['python']

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

How to see the __name__ attribute of a class by using dir() Jennie <nameDOTportua@gmail.com> - 2012-10-20 10:05 +0200
  Re: How to see the __name__ attribute of a class by using dir() Peter Otten <__peter__@web.de> - 2012-10-20 10:24 +0200
    Re: How to see the __name__ attribute of a class by using dir() Jennie <nameDOTportua@gmail.com> - 2012-10-20 10:59 +0200
      Re: How to see the __name__ attribute of a class by using dir() Peter Otten <__peter__@web.de> - 2012-10-20 11:43 +0200
        Re: How to see the __name__ attribute of a class by using dir() Jennie <nameDOTportua@gmail.com> - 2012-10-20 13:19 +0200
        Re: How to see the __name__ attribute of a class by using dir() Jennie <marco.buttu@gmail.com> - 2012-10-20 13:19 +0200
    Re: How to see the __name__ attribute of a class by using dir() Jennie <marco.buttu@gmail.com> - 2012-10-20 10:59 +0200

csiph-web