5

I feel like I have a good grasp of what the __name__ environment variable is in python in general. However, when I print out the __name__ variable from an __init__.py it prints out the name of the directory it's in (aka the package name). How does __name__ get defined in the init file?

Also, does each python file have its own local __name__ variable? because it's constantly changing between files... (maybe I don't understand __name__ as well as I thought I did)


EDIT: I really don't think this question is the same as the __name__ equals __main__ question. I understand what __name__ equals in most python files. I'm just still confused on what it's value is in the __init__ files.

smci
  • 32,567
  • 20
  • 113
  • 146
Joshua Segal
  • 541
  • 1
  • 7
  • 19

1 Answers1

5

__name__ is a "magic" variable within Python's module system. It's simply the module name, or what you import something as. For example, /radical/__init__.py would mean that one could do the following

import radical

The __init__.py is how you indicate to Python that you want a folder treated as a module. This allows module hierarchies to be built from multiple files, rather than one giant file. Take for example this piece of code: /radical/utils.py

import utils from radical

Without the __init__.py Python treats it as an ordinary folder and so it won't have a module name.

If you run a script directly, __name__ is loaded as the __main__ module, which is why if __name__ == '__main__' checks that you're running the file instead of importing it.

Alec
  • 8,529
  • 8
  • 37
  • 63