1

Once a class is constructed (i.e. defined, not instantiated), I can access its dunder attributes.

>>> class Foo:
...    'This is a class.'
>>> Foo.__doc__
'This is a class.'

Is there any way I can access __doc__ while the class is being defined?

class Foo:
    'This is a class.'
    a = Foo.__doc__  # does not work because Foo is not defined yet

Or can this not be done because __doc__ is only assigned by the meta class after the class body has been executed? Is there an alias for it then? How about other dunder attributes/methods?

polwel
  • 597
  • 5
  • 17
  • Related to https://stackoverflow.com/questions/2035423/python-how-to-refer-to-the-class-from-within-it-like-the-recursive-function, and https://stackoverflow.com/questions/13900515/how-can-i-access-a-classmethod-from-inside-a-class-in-python – polwel Feb 21 '18 at 16:08

1 Answers1

1

You cannot access the docstring as an attribute of the class (because the class object doesn't exist yet), but you can grab it directly, like a local variable:

class Foo:
    'This is a class.'
    a = __doc__

This sets the value of a as one would expect:

>>> Foo.a
'This is a class.'

However, I haven't been able to find any information about this behavior in the official documentation. It's unclear if being able to access __doc__ like this is an official feature or a mere implementation detail. If you want to make absolutely sure that your code doesn't rely on what's possibly an implementation detail, you can manually assign to __doc__ like so:

class Foo:
    a = __doc__ = 'This is a class.'

It's a little ugly, but it's guaranteed to work.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • Duh, I was sure your first option was the first thing I tried. Well, I must have done something wrong... Anyway, I am really glad to know that you can *assign* to `__doc__` too. – polwel Feb 22 '18 at 17:38
  • Also, for any future reader that might come across this: I ended up solving my specific problem by using a decorator. Turned out to be much more elegant. – polwel Feb 22 '18 at 17:41