Alan Alan - 1 year ago 57
Python Question

Is there a comprehensive table of Python's "magic constants"?

Where are

, etc. defined, and what are they officially called?
are "magic methods", so right now I'm just referring to them as "magic constants" but I don't even know if that's right.

Google search really isn't turning up anything and even Python's own documentation doesn't seem to have a comprehensive list of them after scanning through the layers of pages.

Answer Source

There is no comprehensive table of those __dunder_names__ (also not their official title!), as far as I'm aware. There are a couple of sources:

  • The only real "magic constant" is __debug__: it's a SyntaxError to attempt to assign to this name. It's covered in the list of constants and mentioned in the context of the assert statement.

  • Another module-level name with specific use by a statement is __all__, which is documented alongside the import statement.

  • __main__ is slightly different, as it's the top-level environment in which a script is executed and is a module in itself, so it gets its own page.

  • Another special module is __future__, for accessing language features that aren't yet mandatory (e.g. print_function to replace the print statement in Python 2).

  • Most of the rest (__name__, __file__, etc.) are added to modules by the import system, so are listed in the import documentation.

There are also many related to objects, for example:

Note that there is nothing particularly "magic" about most of these, they are just regular attributes and can be assigned to as you see fit. However, they are considered reserved for internal Python machinery, so you shouldn't add your own; per the language reference on "reserved classes of identifiers":

Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

That said, there are a couple in common use that I don't think are actually specified anywhere in the official docs, like __author__ and __version__; see e.g. What is the common header format of Python files? and What is the origin of __author__? A few have semi-official status via PEP-8, but that's about it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download