You can turn any Python script that you write into a module that other people can import and use in their own code.
For example;
import superhero
What has happened here???
There is a file in code/superheros
called superhero.py
. The line import superhero
will look in the current directory as well as at the path of any installed modules, to find a file called superhero.py
. It then runs this file, just as if you had typed it into the screen.
This is just a simple Python script, which we can print out using
import inspect
lines = inspect.getsource(superhero)
print(lines)
We can get help on the module using help
help(superhero)
This documentation comes from the class and function documentation put into the file.
You can also use the data, classes and functions in the file, e.g.
ironman = superhero.Superhero(name="Iron Man", weakness="rust")
superhero.battle(ironman, superhero.lex)
superhero.lex.steal("rust")
superhero.battle(ironman, superhero.lex)
One thing to note is that all of the classes, functions and data in the script has been imported into its own namespace, named after the script (e.g. superhero
). We can import the file and put all names into the current namespace using
from superhero import *
battle(ironman, lex)
While any python script can be imported as a module, there are a few conventions you should follow that will make your module easier for others to use.
superhero.py
, which is the first thing written out by help(). This should provide an overview of the module.superhero.py
is bad as it does this, which is why you see "Is it a bird..." printed when you import it!The way to avoid creating any variables or running code is to let the script detect when it is being imported, and to not create any variables if that is the case.
You can detect if your Python script is not being imported using
if __name__ == "__main__":
print("I am not being imported.")
if __name__ == "__main__":
print("I am not being imported")
To show how this works, there is a superhero2.py
script, which is identical to superhero.py
, except all code that should not be run on import is hidden inside the if __name__ == "__main__":
block.
import superhero2
By using if __name__ == "__main__":
we have prevented superhero2.py
from printing anything out when it is imported, and have also prevented it from creating the variables lex
and superman
.
lines = inspect.getsource(superhero2)
print(lines)
You can see this by running the superhero2.py
script directory, e.g. using
! python ./code/superheros/superhero2.py