32

I'm aware of the standard example: if you execute a module directly then it's __name__ global variable is defined as "__main__". However, nowhere in the documentation can I find a precise description of how __name__ is defined in the general case. The module documentation says...

Within a module, the module's name (as a string) is available as the value of the global variable __name__.

...but what does it mean by "the module's name"? Is it just the name of the module (the filename with .py removed), or does it include the fully-qualified package name as well?

How is the value of the __name__ variable in a Python module determined? For bonus points, indicate precisely where in the Python source code this operation is performed.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Jeremy
  • 1
  • 85
  • 340
  • 366
  • 1
    I've seen variations of this question out there, but I'm glad someone has brought the subject more depth. – Nathan Basanese Apr 14 '15 at 04:05
  • Related post - [What does if __name__ == “__main__”: do?](https://stackoverflow.com/q/419163/465053) – RBT Jul 20 '18 at 06:39

2 Answers2

34

It is set to the absolute name of the module as imported. If you imported it as foo.bar, then __name__ is set to 'foo.bar'.

The name is determined in the import.c module, but because that module handles various different types of imports (including zip imports, bytecode-only imports and extension modules) there are several code paths to trace through.

Normally, import statements are translated to a call to __import__, which is by default implemented as a call to PyImport_ImportModuleLevelObject. See the __import__() documentation to get a feel for what the arguments mean. Within PyImport_ImportModuleLevelObject relative names are resolved, so you can chase down the name variables there if you want to.

The rest of the module handles the actual imports, with PyImport_AddModuleObject creating the actual namespace object and setting the name key, but you can trace that name value back to PyImport_ImportModuleLevelObject. By creating a module object, it's __name__ value is set in the moduleobject.c object constructor.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 3
    Additionaly, the `as` subclause in `import` does not change the `__name__` attibute. – andy Jan 26 '15 at 09:02
3

The __name__ variable is an attribute of the module that would be accessible by the name.

import os
assert os.__name__ == 'os'

Example self created module that scetches the import mechanism:

>>> import types
>>> m = types.ModuleType("name of module") # create new module with name
>>> exec "source_of_module = __name__" in m.__dict__ # execute source in module
>>> m.source_of_module
'name of module'

Lines from types module:

import sys
ModuleType = type(sys)
User
  • 14,131
  • 2
  • 40
  • 59