Two double underscore variables#

Python often uses variable and function and method names with double underscores on each end.

For example, as Python sets up to import a module, it defines a variable for itself called __file__.

Experienced Python people often call these variables “dunder” variables, because they have Double UNDERscores on each side.

When you see a dunder variable or function or method, it is almost invariably a variable or function or method that Python has defined, or that Python is using in a special way.

The __file__ variable#

The __file__ variable contains the path to the file that Python is currently importing. You can use this variable inside a module to find the path of the module. For example, let’s say you have a module like this:

%%file example_module.py

# An example Python module
print("Type of __file__ variable is:", type(__file__))
print("__file__ is:", __file__)
Writing example_module.py

If you run this module as a script, __file__ is set:

# Execute as script
%run example_module.py
Type of __file__ variable is: <class 'str'>
__file__ is: /home/runner/work/textbook/textbook/example_module.py

If you import the module, __file__ is also set:

import example_module
Type of __file__ variable is: <class 'str'>
__file__ is: /home/runner/work/textbook/textbook/example_module.py

The __name__ variable#

When Python imports a module, it sets the __name__ variable to be a string containing the name of the module it is importing:

%%file another_example.py

# Another example Python module
print("Type of __name__ variable is:", type(__name__))
print("__name__ is:", __name__)
Writing another_example.py
import another_example
Type of __name__ variable is: <class 'str'>
__name__ is: another_example

If you run the same module as a script, Python is not importing when it runs the code, and __name__ contains the string "__main__":

%run another_example.py
Type of __name__ variable is: <class 'str'>
__name__ is: __main__