Python is a versatile programming language that comes with many built-in modules and packages that extend its functionality. Modules are collections of related functions and data, while packages are collections of related modules.
#Game.py
import draw
def play_game():
...
def main():
result = play_game()
draw.draw_game(result)
# this means that if this script is executed, then
# main() will be executed
if __name__ == '__main__':
main()
#Draw.py
def draw_game():
...
def clear_screen(screen):
...
Python allows you to import modules and packages into your code, giving you access to their functions and data. You can import modules using the import statement, followed by the name of the module.
#Import the draw module
from draw import draw_game
def main():
result = play_game()
draw_game(result)
#game.py
from draw import *
def main():
result = play_game()
draw_game(result)
#game.py
if visual_mode:
# in visual mode, we draw using graphics
import draw_visual as draw
else:
# in textual mode, we print out text
import draw_textual as draw
def main():
result = play_game()
# this can either be visual or textual depending on visual_mode
draw.draw_game(result)
In addition to built-in modules, Python also allows you to create your own modules and packages, which can be shared and reused in other projects. To create a module, you can simply define your functions and data in a .py file, and then import them into your code using the import statement.
#draw.py
def draw_game():
# when clearing the screen we can use the main screen object initialized in this module
clear_screen(main_screen)
...
def clear_screen(screen):
...
class Screen():
...
# initialize main_screen as a singleton
main_screen = Screen()
#Extended Load Path
PYTHONPATH=/foo python game.py
sys.path.append("/foo")
#Various methods of Importing Modules
import foo.bar
from foo import bar
To create a package, you can organize your modules into a directory structure and include an init.py file in each directory. This allows you to import the package and its modules using the same syntax as built-in modules.
Module and Packages Exercise Solution
# Module and Packages Exercise Solution
find_members = []
for member in dir(re):
if "find" in member:
find_members.append(member)
print(sorted(find_members))
In summary, modules and packages are an essential part of working with Python and extend the language’s functionality in many ways. By importing built-in modules and creating your own modules and packages, you can enhance your code’s capabilities and build more robust and scalable applications.