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

Question:

Does anyone know where are __file__, __main__, etc defined? And what are they officially called? __eq__ and __ge__ are "magic methods", so right now I’m just referring to them wholly 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 various pages. Any guidance would be much appreciated on this topic.

Asked By: AlanSTACK

||

Answers:

Short answer: no. For the longer answer, which got badly out of hand, keep reading…


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.

  • There are two special modules, documented in the library reference, which have their own pages:

    • __main__ is the top-level environment in which a script is executed.

    • __future__ is 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. The basic methods for implementing built-in behaviour (like __eq__ and __ge__, as you mention) are listed in the data model documentation. But plenty of other, more specific names exist; for example, there are several related specifically to exceptions, like __cause__ and __traceback__, in the exceptions documentation.


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.


A few others have trodden this path, by the looks of it:

Answered By: jonrsharpe
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.