Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python module


May 10, 2021 Python2


Table of contents


Python module

Modules allow you to logically organize your Python snippppy code.

Assigning relevant code to a module makes your code more useful and understandable.

The module is also a Python object, with random name properties to bind or reference.

Simply put, a module is a file that holds Python code. M odules define functions, classes, and variables. The module can also contain executable code.

Example

Python code in a module called aname is typically found in a aname.py called a file. The following example is a simple module support.py.

def print_func( par ):
   print "Hello : ", par
   return

Import statement

To use the Python source file, simply execute the import statement in another source file, as follows:

import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, if the module is imported in the current search path.

The search path is a list of all directories that the interpreter searches first. If you want to import modules hello.py, you need to put the command at the top of the script:

#coding=utf-8
#!/usr/bin/python
 
# 导入模块
import support
 
# 现在可以调用模块里包含的函数了
support.print_func("Zara")

The above example output results:

Hello : Zara

A module is imported only once, no matter how many times you execute the import. This prevents the import module from being executed over and over again.


From... Import statement

Python's from statement lets you import a specified portion from the module into the current namespace. The syntax is as follows:

from modname import name1[, name2[, ... nameN]]

For example, to import the fibonacci function of the module fib, use the following statement:

from fib import fibonacci

This declaration does not import the entire fib module into the current namespace, it only introduces the fibonacci individual in the fib into the global symbol table of the module executing the declaration.


From... Import statement

It is also possible to import everything from a module into the current namespace, using only the following declaration:

from modname import *

This provides an easy way to import all the items in a module. However, such declarations should not be used too much.


Position the module

When you import a module, the Python parser searches the module location in the following order:

  • The current directory
  • If not in the current directory, Python searches for each directory under the shell variable PYTHONPATH.
  • If you can't find it, Python looks at the default path. Under UNIX, the default path is generally /usr/local/lib/python/

The module search path is stored in the system module's sys.path variable. The variable contains the current directory, PYTHONPATH, and the default directory determined by the installation process.



PYTHONPATH variable

As an environment variable, PYTHONPATH consists of many directories installed in a list. PYTHONPATH has the same syntax as the shell variable PATH.

In Windows systems, the typical PYTHONPATH is as follows:

set PYTHONPATH=c:\python20\lib;

In UNIX systems, the typical PYTHONPATH is as follows:

set PYTHONPATH=/usr/local/lib/python


Namespaces and scopes

A variable is a name (identifier) that has a matching object. A namespace is a dictionary that contains variable names (keys) and their respective objects (values).

A Python expression can access variables in local and global namespaces. If a local variable and a global variable are renamed, the local variable overrides the global variable.

Each function has its own namespace. The scope rules of the class's methods are the same as usually functions.

Python intelligently guesses whether a variable is local or global, assuming that any variable assigned within a function is local.

Therefore, if you want to assign a global variable a value in a function, you must use a global statement.

The expression of global VarName tells Python that VarName is a global variable so that Python does not look for it in the local namespace.

For example, we define a variable money in the global namespace. W e then assign a value to the variable money within the function, and Python assumes that money is a local variable. H owever, we did not declare a local variable money before the visit, and the result was a UnboundLocalError error. Uncommenting the global statement solves the problem.

#coding=utf-8
#!/usr/bin/python
 
Money = 2000
def AddMoney():
   # 想改正代码就取消以下注释:
   # global Money
   Money = Money + 1
 
print Money
AddMoney()
print Money


Dir() function

The dir() function is a list of sequenced strings with a name defined in a module.

The list returned contains all the modules, variables, and functions defined in one module. Here's a simple example:

#coding=utf-8
#!/usr/bin/python
 
# 导入内置math模块
import math
 
content = dir(math)
 
print content;

The above example output 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__ the name of the module, __file__ the import file name of the module.



Globals() and locals() functions

Depending on where the call is made, the globals() and locals() functions can be used to return names in global and local namespaces.

If you call locals() inside a function, all the names that can be accessed within the function are returned.

If you call globals() inside a function, all global names that are accessible in the function are returned.

The return types of both functions are dictionaries. So names can be extracted using the keys() function.



The reload() function

When a module is imported into a script, the code at the top of the module is executed only once.

Therefore, if you want to re-execute the code at the top of the module, you can use the reload() function. T he function re-imports previously imported modules. The syntax is as follows:

reload(module_name)

Here, module_name the name of the module directly, not in the form of a string. For example, if you want to overload the hello module, here's it:

reload(hello)


The package in Python

A package is a hierarchical file directory structure that defines a Python application environment consisting of modules and subpases, subpases under subpases, and so on.

Consider a file in the Phone pots.py directory. This file has the following source code:

#coding=utf-8
#!/usr/bin/python
 
def Pots():
   print "I'm Pots Phone"

Similarly, we have two other files that hold different functions:

  • Phone/Isdn .py contains function Isdn()
  • Phone/G3.py contains function G3()

Now, create a file file under the phone directory__init__.py:

  • Phone/__init__.py

When you import a Phone, in order to be able to use all functions, you need to use __init__.py in the __init__.py, as follows:

from Pots import Pots
from Isdn import Isdn
from G3 import G3

When you add this code __init__.py, the classes are all available when you import the Phone package.

#coding=utf-8
#!/usr/bin/python
 
# Now import your Phone Package.
import Phone
 
Phone.Pots()
Phone.Isdn()
Phone.G3()

The above example output results:

I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone

For example, we've placed only one function in each file, but you can actually place many functions. You can also define Python's classes in these files, and then build a package for those classes.