6.1. Modules & Packages - JulTob/Python GitHub Wiki

Modules are also called libraries or packages.

In python is a .py file. The name of the module is the name of the file.

A Python module can have a set of functions, classes or variables defined and implemented.

module.py

To import a package:

`import module`
### Call
`module.function()`

# OR

from module import function
### Call
function()

Import all objects

from module import *
### Call
function()

Import all objects in namespace

from module import * as alias
### Call
alias.function()

Conditional Import all Objects in namespace

if mode:
   from module_1 import * as alias
else:
   from module_2 import * as alias

# Call
alias.function()

Example

if visual:  # Visual or textual output?
  from visual import * as put
else:
  from textual import * as put

# Call
put.play_game()

You may have noticed that when importing a module, a .pyc file appears, which is a compiled Python file. Python compiles files into Python bytecode so that it won't have to parse the files each time modules are loaded. If a .pyc file exists, it gets loaded instead of the .py file, but this process is transparent to the user.

Initialization

The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. If another module in your code imports the same module again, it will not be loaded twice but once only - so local variables inside the module act as a "singleton" - they are initialized only once.


#  Module.py
def function():
...
class Stuff():
...
property = "Value"

Add Path to module

Additional directories to look for modules

PYTHONPATH=/foo python game.py
_____________________ Or ________________________
sys.path.append("/foo")  # before import