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 your current directory called superhero.py
. The line import superhero
will look in the current directory, 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
for line in open("superhero.py", "r").readlines():
print(line, end="")
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.
for line in open("superhero2.py", "r").readlines():
print(line, end="")
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
.
You can see this by running the superhero2.py
script directory, e.g. using
! python superhero2.py
! python superhero2.py
Use the "New Text File" option in the Jupyter Home to create a new python text file called morse.py
. Copy the below class into this file.
class Morse:
def __init__(self):
self._letter_to_morse = {'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.',
'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--',
'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-',
'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..',
'0':'-----', '1':'.----', '2':'..---', '3':'...--', '4':'....-',
'5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.',
' ':'/' }
self._morse_to_letter = {}
for letter in self._letter_to_morse.keys():
self._morse_to_letter[ self._letter_to_morse[letter] ] = letter
def encode(self, message):
morse = []
for letter in message:
morse.append( self._letter_to_morse[letter.lower()] )
return morse
def decode(self, morse):
message = []
for code in morse:
message.append( self._morse_to_letter[code] )
return "".join(message)
Add documentation to this class, and to the module. Next, import the module and get help using the commands
import morse
help(morse)
Does your documentation make sense?
Create some checks of your module that should not be run when the module is imported (i.e. only run directly). The checks should be, e.g.
morse = Morse()
for message in ["Hello world", "something to encode", "test message"]:
test = morse.decode( morse.encode(message) )
if message.lower() == test:
print("Success: %s" % message)
else:
print("Failed: %s" % message)
Validate that the check doesn't run on import using
import morse
Validate that the check runs from the command line using
! python morse.py
! python morse_answer.py