0% found this document useful (0 votes)
15 views4 pages

Overview of Python Modules

Modules allow you to organize Python code logically and make it reusable. A module is a Python file with a .py extension that can define functions, classes, and variables. The import statement is used to import modules so their contents can be accessed. Modules are only loaded once, regardless of how many times they are imported. Namespaces and scoping rules determine whether variables are local or global.

Uploaded by

sudeepdruvan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views4 pages

Overview of Python Modules

Modules allow you to organize Python code logically and make it reusable. A module is a Python file with a .py extension that can define functions, classes, and variables. The import statement is used to import modules so their contents can be accessed. Modules are only loaded once, regardless of how many times they are imported. Namespaces and scoping rules determine whether variables are local or global.

Uploaded by

sudeepdruvan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON MODULES

[Link] rialspo [Link] m/pytho n/pytho n_mo dule [Link] Co pyrig ht © tuto rials po [Link] m

A module allows you to log ically org anize your Python code. Grouping related code into a module makes the
code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind
and reference.

Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A
module can also include runnable code.

Example:
T he Python code for a module named aname normally resides in a file named [Link]. Here's an example of a
simple module, [Link]

def print_func( par ):


print "Hello : ", par
return

The import Statement:


You can use any Python source file as a module by executing an import statement in some other Python source
file. T he import has the following syntax:

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

When the interpreter encounters an import statement, it imports the module if the module is present in the search
path. A search path is a list of directories that the interpreter searches before importing a module. For example,
to import the module [Link], 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 the above code is executed, it produces the following result:

Hello : Zara

A module is loaded only once, reg ardless of the number of times it is imported. T his prevents the module
execution from happening over and over ag ain if multiple imports occur.

The from...import Statement


Python's from statement lets you import specific attributes from a module into the current namespace. T he
from...import has the following syntax:

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

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

from fib import fibonacci

T his statement does not import the entire module fib into the current namespace; it just introduces the item
fibonacci from the module fib into the g lobal symbol table of the importing module.

The from...import * Statement:


It is also possible to import all names from a module into the current namespace by using the following import
statement:

from modname import *

T his provides an easy way to import all the items from a module into the current namespace; however, this
statement should be used sparing ly.

Locating Modules:
When you import a module, the Python interpreter searches for the module in the following sequences:

T he current directory.

If the module isn't found, Python then searches each directory in the shell variable PYT HONPAT H.

If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.

T he module search path is stored in the system module sys as the [Link] variable. T he [Link] variable
contains the current directory, PYT HONPAT H, and the installation-dependent default.

The PYTHONPATH Variable:


T he PYT HONPAT H is an environment variable, consisting of a list of directories. T he syntax of PYT HONPAT H
is the same as that of the shell variable PAT H.

Here is a typical PYT HONPAT H from a Windows system:

set PYTHONPATH=c:\python20\lib;

And here is a typical PYT HONPAT H from a UNIX system:

set PYTHONPATH=/usr/local/lib/python

Namespaces and Scoping :


Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and
their corresponding objects (values).

A Python statement can access variables in a local namespace and in the global namespace. If a local and a g lobal
variable have the same name, the local variable shadows the g lobal variable.

Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.

Python makes educated g uesses on whether variables are local or g lobal. It assumes that any variable assig ned
a value in a function is local.

T herefore, in order to assig n a value to a g lobal variable within a function, you must first use the g lobal statement.

T he statement global VarName tells Python that VarName is a g lobal variable. Python stops searching the local
namespace for the variable.

For example, we define a variable Money in the g lobal namespace. Within the function Money, we assig n Money
a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local
variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the g lobal statement
fixes the 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

The dir( ) Function:


T he dir() built-in function returns a sorted list of string s containing the names defined by a module.

T he list contains the names of all the modules, variables and functions that are defined in a module. Following is a
simple example:

#!/usr/bin/python

# Import built-in module math


import math

content = dir(math)

print content;

When the above code is executed, it produces the following result:

['__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 module's name, and __file__ is the filename from which the
module was loaded.

The globals() and locals() Functions:


T he globals() and locals() functions can be used to return the names in the g lobal and local namespaces
depending on the location from where they are called.

If locals() is called from within a function, it will return all the names that can be accessed locally from that function.

If g lobals() is called from within a function, it will return all the names that can be accessed g lobally from that
function.

T he return type of both these functions is dictionary. T herefore, names can be extracted using the keys()
function.

The reload() Function:


When the module is imported into a script, the code in the top-level portion of a module is executed only once.

T herefore, if you want to reexecute the top-level code in a module, you can use the reload() function. T he
reload() function imports a previously imported module ag ain. T he syntax of the reload() function is this:

reload(module_name)

Here, module_name is the name of the module you want to reload and not the string containing the module name.
For example, to reload hello module, do the following :

reload(hello)

Packag es in Python:
A packag e is a hierarchical file directory structure that defines a sing le Python application environment that
consists of modules and subpackag es and sub-subpackag es, and so on.
Consider a file [Link] available in Phone directory. T his file has following line of source code:

#!/usr/bin/python

def Pots():
print "I'm Pots Phone"

Similar way, we have another two files having different functions with the same name as above:

Phone/[Link] file having function Isdn()

Phone/[Link] file having function G3()

Now, create one more file __init__.py in Phone directory:

Phone/__init__.py

T o make all of your functions available when you've imported Phone, you need to put explicit import statements in
__init__.py as follows:

from Pots import Pots


from Isdn import Isdn
from G3 import G3

After you've added these lines to __init__.py, you have all of these classes available when you've imported the
Phone packag e.

#!/usr/bin/python

# Now import your Phone Package.


import Phone

[Link]()
[Link]()
Phone.G3()

When the above code is executed, it produces the following result:

I'm Pots Phone


I'm 3G Phone
I'm ISDN Phone

In the above example, we have taken example of a sing le functions in each file, but you can keep multiple functions
in your files. You can also define different Python classes in those files and then you can create your packag es out
of those classes.

Common questions

Powered by AI

When a module is imported, Python searches for it in a specific sequence: first in the current directory, then in directories listed in the PYTHONPATH environment variable, and finally, in the system's default module directory. This search path is stored in the sys.path variable. If the module cannot be found in any of these locations, the import will fail .

The 'from module import *' statement imports all public names from a module into the current namespace, potentially overwriting existing names and causing confusion or naming conflicts. This practice can lead to debugging difficulties, as it is not clear which module a name was imported from. This statement should be used sparingly to avoid namespace pollution and ensure code clarity and maintainability .

Using global variables in Python functions can lead to unpredictable behavior and make tracking changes across the code difficult, as global variables can be altered from anywhere in the program. This can increase the risk of bugs and reduce code clarity. To mitigate these issues, the 'global' statement should be used judiciously, and it’s often better to refactor code to reduce global variables' usage by encapsulating data within classes or passing variables explicitly as function arguments .

Modules in Python are used to logically organize code by grouping related functionalities, such as functions, classes, and variables, within a single file, making the code easier to understand and use. The import statement allows a Python source file to be used as a module in another Python source file by specifying the module to be imported. When executing an import statement, the interpreter loads the module if it exists in the search path, which includes the current directory, directories in PYTHONPATH, and default directories .

Modifying the PYTHONPATH environment variable affects Python's module search path by adding custom directories where the interpreter will look for modules at import time. By setting directories in PYTHONPATH, developers can include paths to additional locations that are not covered by the default path or current directory, hence expanding the flexibility of module organization and deployment. This is especially useful in complex projects with custom libraries that are not installed in standard locations .

The reload() function in Python is used to re-import a previously imported module, allowing the top-level code of the module to be re-executed. This can be particularly useful during code development and testing, where a module's code may be frequently updated and tested without restarting the Python interpreter. By reloading the module, developers can ensure that the latest version is being utilized .

Python packages allow for hierarchical directory structures that include modules and submodules. An example is a package named 'Phone', which contains modules like 'Pots.py', 'Isdn.py', and 'G3.py'. Creating an '__init__.py' file in the 'Phone' directory allows the package to be imported as a single unit, aggregating the different modules. By including import statements in '__init__.py', such as 'from Pots import Pots', these modules can be accessed via 'import Phone' in other scripts, facilitating organized codebases .

Local and global namespaces refer to the scopes within which variable names can be resolved. Local namespaces are specific to functions, while global namespaces are accessible throughout the module. In a function, Python assumes variables assigned a value are local unless explicitly declared global using the 'global' statement. If a local and global variable share a name, the local variable will overshadow the global variable within the function's scope .

The globals() function returns a dictionary of the global namespace, which includes all variables and functions accessible globally within the module where the function is called. In contrast, the locals() function returns a dictionary containing the local namespace when called inside a function, encompassing all variables accessible locally within that function. Both functions return dictionary types, allowing keys() to extract available names .

The 'dir()' function returns a sorted list of strings containing the names of attributes defined in a module, including variables, functions, and classes. This can be useful for exploring a module's functionality and understanding what objects are available for use. For example, running 'dir(math)' would list all mathematical functions and constants available in the math module, such as 'acos', 'sin', 'pi', etc., allowing users to utilize these resources effectively .

You might also like