A module can logically organize Python code. Transfer relevant code into a module to make the code easier to understand and use. Modules are Python objects that can bind and borrow arbitrary named properties.
Simply put, a module is a file of Python code. A module can define functions, classes, and variables. The module may also include runnable code.
example:
The module name of Python code is usually located in a name. Here is a simple module as an example
def print_func( par ): print "Hello : ", par return
import statement:
Any Python source file can be used as a module by executing import statements in some other Python source files. The syntax of import is as follows:
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if the module appears in the search path. The search path is a directory list that the interpreter searches before importing the module. For example, to import a module, you need to put the following command at the top of the script:
#!/usr/bin/python # Import module support import support # Now you can call defined function that module as follows support.print_func("Zara")
When executing the above code, the following result is produced:
Hello : Zara
A module is loaded once, regardless of the number of imports. This prevents multiple imports from happening on module execution.
from...import statement
Python's from statements can import specific properties from a module into the current namespace. The syntax from...import is as follows:
from modname import name1[, name2[, ... nameN]]
For example, import the function fibonacci from the module fib, using the following statement:
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces fibonacci to import the global symbol table column of the module from the module fib.
from...import * statement:
It can also import all names from the module to the current namespace by using the following import statement:
from modname import *
This provides an easy way to import all projects from the module to the current namespace; however, this statement should be used with caution.
Positioning module:
When importing a module, search the following sequence modules by the Python interpreter:
- Current directory
- If the module is not found, then Python searches for each directory in the shell variable PYTHONPATH
- If all these methods fail, Python checks the default path. On UNIX, the default path is normal /usr/local/lib/python/
The module search path is stored in the system module sys as the variable described. The variables in include the current directory, PYTHONPATH and related default installations.
PYTHONPATH variable:
In PYTHONPATH is an environment variable, including in the directory list. The syntax shell variable PATH of PYTHONPATH is the same.
Here is a typical PYTHONPATH for Windows:
set PYTHONPATH=c:\python20\lib;
Here is a typical PYTHONPATH for UNIX systems:
set PYTHONPATH=/usr/local/lib/python
Namespace and scope:
The variable name (identification) is mapped to the object. A namespace is a dictionary of the variable name (key) and its corresponding object (value).
Python statements can access variables in both local namespace and global namespace. If the local and global variables have the same name, the local variable masks the global variable.
Each function has its own namespace. Class methods follow the same scope rules as normal functions.
Python makes assumption guesses about whether a variable is local or global. It assumes that the values in any variable assignment function are local.
Therefore, in order to assign the value in a function to a global variable, a global statement must be used first.
Declaration global VarName tells Python that VarName is a global variable. Python stops looking for the local namespace for this variable.
For example, the variable Money we define in the global namespace. In the Money of the function, we give the value of Money, so Python assumes that Money is a local variable. However, we set it, so an UnboundLocalError is the value of the local variable Money visited before the result. Cancelling the global statement solves this problem.
#!/usr/bin/python Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money Money = Money + 1 print Money AddMoney() print Money
dir( ) function:
Use the dir() built-in function to return a sorted list of strings containing the name defined in a module.
This list contains the names of all modules, variables, and functions defined in one module. Here is a simple example:
#!/usr/bin/python # Import built-in module math import math content = dir(math) print content; When executing the above code,Produce the following results: ['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the name of the module and __file__ is the file name of the module loaded from it.
globals() and locals() functions:
The globals() and locals() functions can be used to return names in global and local namespaces based on locations they are called.
If locals() is called in a function, it returns all names that can be accessed locally from the function.
If globals() is called from a function, it returns all names that can be accessed from the global function.
The return type of these two functions is a dictionary. Therefore, the name can be extracted using the keys() function.
reload() function:
When the module is imported into a script, the code in the top-level part of a module is executed only once.
Therefore, if you want to re-execute the top-level code module, you can use the reload() function. The reload() function imports the previously imported module. The syntax of the reload() function is as follows:
reload(module_name)
Here, module_name is the name of the module that is to be reinstalled and does not contain the module name string. For example, to reload the hello module:
reload(hello)
Packages in Python:
Packages are hierarchical file directory structures used to define a single Python application environment consisting of modules and subpackages and subpackages.
Consider a file available in the Phone directory. The source code of this file is as follows:
#!/usr/bin/python def Pots(): print "I'm Pots Phone"
Similar approach, we have different functions with the other two files with the same name as above:
- Phone/file has functions Isdn()
- Phone/ file has function G3()
Now, create one more file __init__.py in the Phone directory:
Phone/__init__.py
In order to make all functions available, when importing Phone, you need to put the explicit import statement of __init__.py as follows:
from Pots import Pots from Isdn import Isdn from G3 import G3
When these lines are added to __init__.py, then all these classes are imported for use in the Phone package.
#!/usr/bin/python # Now import your Phone Package. import Phone () () Phone.G3()
When executing the above code, the following result is produced:
I'm Pots Phone I'm 3G Phone I'm ISDN Phone
In the example above we take examples of a single function per file, but can retain multiple functions in the file. Different Python classes can also be defined in these files, and those classes can be created outside the package.