0

Running a script from the command line, the __name__ attribute of that script will be '__main__'. But importing that script from a different location, the __name__ attribute of that module will be the name of the script.

How does python know what the value of __name__ should be? Can a script tell that it's being imported, and set the __name__ attribute accordingly?

2
  • In case it is a module __name__ is the name of the module. Commented Aug 8, 2017 at 22:37
  • @WillemVanOnsem edited for accuracy Commented Aug 8, 2017 at 22:38

2 Answers 2

1

From the docs

The import machinery fills in these attributes on each module object during loading, based on the module’s spec, before the loader executes the module.

__name__
The __name__ attribute must be set to the fully-qualified name of the module. This name is used to uniquely identify the module in the import system.

So these magic attributes are assigned during the so-called "import machinery". You can read more details about that system in the docs as well.

Sign up to request clarification or add additional context in comments.

Comments

1

Q: How does python know what the value of __name__ should be?

Well, if you write import foo Python will look for a module named 'foo' and set its name to 'foo'.

Q: Can a module tell that it's being imported, ...

Yes, it can. Usually people do that with if __name__ == '__main__' -- if the test passes, it generally means that the module is being executed, if it fails it generally means that it is being imported.

A particular case where this test will fail is when you have a module named __main__ (in a file named __main__.py).

If you want to be 100% more sure, you can inspect the frames and see if the module is on top of the stack:

f = sys._getframe()
if f.f_back is None:
    # We're at the top of the stack: this module is being executed.
else:
    # There's a frame on top of us: this module has been imported.

Q: ... and set the __name__ attribute accordingly?

And yes, you can change __name__ to whatever you want by simply setting it:

__name__ = 'bar'

Although there's no reason to do so, other than generating confusion and possibly introducing bugs.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.