Python Modules With Advanced Examples

This article entitled Python Modules is a continuation of the previous article entitled Python Function.

A Python Module is a way that allows you to make your code readable and well-organized and a module is an object with arbitrarily named attributes that can be used for reference and binding.

What is Python Module?

In Python, a module is a file that contains statements and definitions and a module can also be defined as classes, variables, and a function.

Further, a module can also be an executable code or a group of related code inside the module so that the code can be easier to read and understand.

Example

def print_func( greet ):
   print ("Good day true heroes : ", greet)
   return

How many modules are in Python?

Python libraries contain over 200 modules.

What are the basic modules in Python?

A basic module is a file with a ( .py ) extension that contains a Python code that will be imported within another python code.

Import statement in Python

Python allows you to use any source Python file as a module by only executing the import statement in some other source doc file.

Syntax

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

Once the interpreter will encounter an import statement it will automatically import the module once the module is there in the search path.

A search path is a directory-sorted list that the interpreter will look at or search before importing the module.

Example

# Import module support
import support

# Now you can call defined function that module as follows
support.print_func("Glenn")

Output

Good day true heroes : Glenn

The module is loaded at once for all the number of times that can be imported this can allow preventing the program execution from iterating over and over again once there are multiple imports will occur.

Python from…import statement

The Python from…statement allows you to import specific (attributes) from the module into the present namespace.

Syntax

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

Example

from fib import fibonacci

This statement will not import the entire fib module in the present namespace. It just only introduces one item the Fibonacci from the fib module into a global table of the module which has been imported.

Python from…import * statement

A Python from…import * statement is a way to import all the names from the module that was imported in the present namespace.

Syntax

from modname import *

This import statement is the easiest way to import all items from the module into the present namespace and the statement should be used frequently.

Locating modules in Python

Once you already import the module the interpreter will search for the module.

  • The current import directory
  • Once the module is not found, Python will search each directory in the variable shell or PYTHONPATH.
  • Or else it will be false, Python will check the default path on the UNIX and the default path is normally in your local directory.

PYTHONPATH Variable

A variable PYTHONPATH is an environment variable that consists the all the directory lists. The PYTHONPATH and shell variable PATH have the same syntax.

PYTHONPATH Syntax for windows system

set PYTHONPATH = c:\python30\lib;

PYTHONPATH Syntax for UNIX system

set PYTHONPATH = /usr/local/lib/python

Python namespaces and scoping

A namespace is the dictionary name of the variable (keys) and the object that corresponds to the values. The variable is the names or identifiers of the object maps.

The statement can access the variables from the local and global namespace. Once the global and local variable has the same name, the local variable will shadow the global.

Every function has its own local namespace and the class methods will follow the same scoping rule as a function that is ordinary.

Python makes a bright idea for guessing the variables whether it is global or local. They will assume that any variable will be assigned a value in the local Python script.

In simple mean, you need to assign a value to the global variable inside the function class, Then it must first use the global statement.

A statement global nameOfVar will tell Python that the nameOfVar is (global variable) and Python will stop searching the local namespace for a variable.

Example

cost = 1500
def Pay():
   # Uncomment the following line to fix the code:
   # global cost
   cost = cost + 1

print (cost)
Pay()
print (cost)

Python locals() and globals() function

In Python, locals() and globals() functions are used to return the variable names in the local and global namespaces that depend on the location where they are called.

Once the local variable was called within the function, the names will return all that can be accessed locally from the function.

Once the globals() are called within the function, the names will return all which can be accessed globally from the function.

A dictionary is the return type of both functions, It means that the names can be extracted with the use of function name keys().

dir() function in Python

A dir() is an in-built function in Python that returns a list of sorted strings that contain the names of the defined module search path.

Example

# Import built-in module pandas
import pandas

pandas = dir(pandas)
print (pandas)

Output

['BooleanDtype', 'Categorical', 'CategoricalDtype', 'CategoricalIndex', 'DataFrame', 'DateOffset', 'DatetimeIndex', 'DatetimeTZDtype', 'ExcelFile', 'ExcelWriter', 'Flags', 'Float32Dtype', 'Float64Dtype', 'Float64Index', 'Grouper', 'HDFStore', 'Index', 'IndexSlice', 'Int16Dtype', 'Int32Dtype', 'Int64Dtype', 'Int64Index', 'Int8Dtype', 'Interval', 'IntervalDtype', 'IntervalIndex', 'MultiIndex', 'NA', 'NaT', 'NamedAgg', 'Period', 'PeriodDtype', 'PeriodIndex', 'RangeIndex', 'Series', 'SparseDtype', 'StringDtype', 'Timedelta', 'TimedeltaIndex', 'Timestamp', 'UInt16Dtype', 'UInt32Dtype', 'UInt64Dtype', 'UInt64Index', 'UInt8Dtype', '__builtins__', '__cached__', '__doc__', '__docformat__', '__file__', '__getattr__', '__git_version__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_config', '_hashtable', '_is_numpy_dev', '_lib', '_libs', '_np_version_under1p18', '_testing', '_tslib', '_typing', '_version', 'api', 'array', 'arrays', 'bdate_range', 'compat', 'concat', 'core', 'crosstab', 'cut', 'date_range', 'describe_option', 'errors', 'eval', 'factorize', 'get_dummies', 'get_option', 'infer_freq', 'interval_range', 'io', 'isna', 'isnull', 'json_normalize', 'lreshape', 'melt', 'merge', 'merge_asof', 'merge_ordered', 'notna', 'notnull', 'offsets', 'option_context', 'options', 'pandas', 'period_range', 'pivot', 'pivot_table', 'plotting', 'qcut', 'read_clipboard', 'read_csv', 'read_excel', 'read_feather', 'read_fwf', 'read_gbq', 'read_hdf', 'read_html', 'read_json', 'read_orc', 'read_parquet', 'read_pickle', 'read_sas', 'read_spss', 'read_sql', 'read_sql_query', 'read_sql_table', 'read_stata', 'read_table', 'read_xml', 'reset_option', 'set_eng_float_format', 'set_option', 'show_versions', 'test', 'testing', 'timedelta_range', 'to_datetime', 'to_numeric', 'to_pickle', 'to_timedelta', 'tseries', 'unique', 'util', 'value_counts', 'wide_to_long']

Python reload() function

A reload function is a built-in function in Python that can be used to reload the imported module previously or the loaded module.

For an instance that the module is already imported into the script, the top-level portion of the code will be executed once.

It simply means that if you want to rerun a module in a top-level code, that’s the reload() function can be used.

Syntax

reload(nameOfModule)

The nameOfModule is the module name that you want to reload and does not contain a string in the module name.

Example

reload(True heroes use sourcecodehero)

Output

True heroes use sourcecodehero

Summary

In summary, you have read about Python Modules. We also discussed in this article what is Python Module, how many modules are in Python, what are the basic modules, import statement, locating modules.

Along with are PYTHONPATH variable, namespace and scoping, locals() and global() function, dir() function, and reload() function.

I hope this article could help you a lot to continue pursuing learning this powerful programming language.

If you want to learn more check out my previous and latest articles for more career-changing articles.

Leave a Comment