Last active
January 13, 2022 10:39
-
-
Save susanBuck/b6204ce440d99e94af7880f4103de255 to your computer and use it in GitHub Desktop.
Python Module Name Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The technical term for a text file of Python code (what we've been creating all semester) is a module. | |
# | |
# This file you're looking at right now, programA.py, is a module. | |
# | |
# The file name acts as the module name. | |
# I.e. for this file programA.py, the corresponding module name is `programA`. | |
# | |
# That's why if we wanted to import this file into another file, we'd just say `import programA`, not `import programA.py` | |
# | |
# Ok, now that we know what a module is, let's look towards what __name__ is... | |
# | |
# Within a module, that module's name is avilable as a built-in Python variable called `__name__` | |
# | |
# If you run a module directly, the module name (__name__) is set to __main__. | |
# | |
# If you import a module into another module, the module name (__name__) is the file name. | |
# | |
# To see this in action, run programA.py and note the output. | |
# Then run programB.py (which imports programA) and note the output. | |
# | |
print "module name: " + __name__ | |
# If this module is being run directly... | |
if __name__ == '__main__': | |
print 'This program, programA, is being run by itself.' | |
# If this module is being imported... | |
else: | |
print 'programA is being imported from another file.' | |
# Purpose: | |
# Encapsulating the code you want to execute inside a `if __name__ == '__main__':` statement is not necessary. | |
# However, it can be useful if you only want certain code to run when that file is being run directly, | |
# versus when it's being imported to another file. | |
# | |
# The best example of this is with our picture.py module-- | |
# In that file there are numerous tests we only want to run when that file is run directly, | |
# But we don't want those same tests to run when we're importing picture.py into another file. | |
# To accomplish this, the tests are nested in an `if __name__ == '__main__':` | |
# Ref: https://docs.python.org/2/tutorial/modules.html |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import programA | |
# Expected output when you run this file: | |
# module name: programA | |
# I am being imported from another file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment