Modules
Eventually a codebase becomes so big that you need to split things into different files, known as modules.
A module is a file containing python statements and definitions, the name of the module is the same as the
name of the file, without the py
extension.
We can define some code in a file named game.py
and import it into out main.py
file.
folder/
main.py
game.py
class Player:
health = 100
position = [0,0,0]
def __int__(self,name = "Player"):
self.name = name
def move(self,x,y,z):
self.position[0] += x
self.position[1] += y
self.position[z] += z
def is_alive(self):
return self.health > 0
And now we can import it in our main file, or any other file, using an import
statement. Importing
the module brings it into scope and lets us use any of the code from the game
module.
import game
player = game.Player("Johnny Storm")
You may import specific defitions from the module, allowing you to use the name directly without the module name.
from game import Player
player = Player("Sue Storm")
Similarly you can import everything from the module using an asterisk (*
).
from game import *
You can import the module using an alias, and it would be available under that alias.
import game as g
player = g.Player("Franklin Richards")
Main function
The name of the module is provided using the __name__
variable, which is available in every
module. Every module will be the name of it’s file, minus the extension, except the current running
module which will be named __main__
. So if we run py game.py
and got its __name__
it would be __main__
.
When a module is imported all the statements in the module will run, this can cause issues
if unexpected things run, like network requests which can slow things down. We can prevent
this by defining a main function and only running that if __name__
is __main__
.
def main():
print("Initializing resources")
if __name__ == "__main__":
main()
Standard library
Python comes with a lot of built-in modules that will be useful to most users, known as the standard library. Most programming languages have a standard library, and they come with things such as:
- Json parsing
- File management
- Cryptographic functions
- Operating system utilities
from math import sqrt
# Use the sqrt function from the standard library
squared = sqrt(24)
PIP
We can import external modules in a similar way