Advance Python Modules – How to Create & Import with dir Function
Free Python course with 25 real-time projects Start Now!!
In this Python Modules tutorial, we will discuss what is a module in Python programming language? Moreover, we will talk about how to create python modules and import modules in python.
Along with this, we will learn how can we execute python module as a script, standard Python modules, and Python dir functions.
So, let’s start Python Modules Tutorial.
What is Python Module?
Python module is but a piece of code.
Exiting the interpreter destroys all functions and variables we created. But when we want a longer program, we create a script.
With Python, we can put such definitions in a file, and use them in a script, or in an interactive instance of the interpreter. Such a file is a module.
If you face any difficulty in article on Python modules, ask us in comments.
In essence, a module is a file that contains Python statements and definitions. A Python modules looks like this:
How to Create Python Modules?
Let’s create a Python modules ‘calc’.
Microsoft Windows [Version 10.0.16299.309]
(c) 2017 Microsoft Corporation. All rights reserved.
And this is what we put inside the module calc.py:
def add(a,b): return a+b def sub(a,b): return a-b def mul(a,b): return a*b def div(a,b): return a/b def exp(a,b): return a**b def floordiv(a,b): return a//b
Also, calc is a package we create, and we place __init__.py inside it (Refer to Python Packages).
How can we Import Modules in Python?
Now, to import Python modules, we first get to the Desktop in Python.
>>> import os >>> os.chdir('C:\\Users\\lifei\\Desktop\\calc') >>> import calc >>>
To find the name of this module, we can use the __name__ attribute.
We can now use functions from this module:
We can also assign one of these functions a name:
>>> fd=calc.floordiv >>> fd(5.5,4)
More on Python Modules and Importing
Python modules may contain anything from executable statements to function definitions. Such statements initialize the module. Hence, they execute only once, when we import the module.
However, they also run if we execute the file as a script. Each module uses its own private symbol table globally for all of its functions.
So, its author can use global variables in the module without worrying that they will accidentally clash with a user’s global variables.
A module can always import other modules in Python. In fact, we can place import statements at the beginning of a module/script, but we don’t ‘need’ to.
This places the imported module’s name in the importing module’s symbol table.
We can also selectively import functions from a Python modules:
>>> from calc import div as d,floordiv as fd >>> d(9,4)
We can also import all from a module:
>>> from calc import * >>> floordiv(9,4)
This will import all names other than those beginning with an underscore(_). However, we disparage this use, as it makes for poorly readable code.
We can also import a module under an alias.
>>> import calc as cal >>> cal.sub
<function sub at 0x0655CC90>
How to Execute Python Modules as Scripts?
Look at the following code:
def add(a,b): print(a+b) def sub(a,b): print(a-b) def mul(a,b): print(a*b) def div(a,b): print(a/b) def exp(a,b): print(a**b) def floordiv(a,b): print(a//b) if __name__ == "__main__": import sys if int(sys.argv)==1: add(int(sys.argv),int(sys.argv)) elif int(sys.argv)==2: sub(int(sys.argv),int(sys.argv))
These last few lines let us use the sys module to deal with command line arguments. To execute subtraction, this is what we type in the command prompt:
C:\Users\lifei\Desktop\calc>python calc.py 2 3 4
This way, you can complete the code for other operations as well. Hence, we’ve created a script. But we can also import this normally like a module:
>>> import calc >>>
We may want to run a module as a script for testing purposes.
Any Doubt yet in Python Modules? Please Comment.
Python Module Search Path
Whenever we import Python modules, say eggs, the interpreter searches a built-in version. If not found, it searches for a file named eggs.py under a list of directories given by variable sys.path.
This variable is initialized from the following locations:
- The directory holding the input script (or the current directory, in case no file is specified).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default.
Once initialized, a Python program may modify sys.path.
Compiled Python Files
In an attempt to speed up loading a module, Python will cache each module’s compiled version in the __pycache__ directory. It does so under the name module.version.pyc.
Here, the version encodes the compiled file’s format. For instance, under CPython 3.3, we’ll have eggs.py as __pycache__/eggs.cpython-33.pyc.
This allows compiled modules from different Python versions and releases to coexist.
These compiled modules are platform-independent. If the compiled version is out of date, Python recompiles it automatically.
Python Standard Modules
And like we’ve always said, Python ships with a library of standard Python modules. While some of them are built into the interpreter, we can create our own.
The standard ones lend us extra functionality, in turn reducing the need to code too much. Other times, they provide efficiency to a programmer, in cases like providing access to operating system primitives, the likes of system calls.
The module sys is built into every Python interpreter. However, some modules are only available to certain operating platforms.
For instance, the winreg module is only available to Windows programmers.
The sys module will also tell you which version of Python you are using.
>>> import sys >>> sys.version
Python dir() Function
The dir() is a built-in function that returns a sorted list of all the names that a Python modules defines.
>>> for i in dir(calc): print(i)
And without any arguments, dir() returns a lilst of the names that we have defined currently.
To get a list of built-in functions and variables, we do the following, instead:
>>> import builtins >>> dir(builtins)
This was all on Python modules. Hope the Python Modules article was informative.
Python Interview Questions on Modules
- What is module in Python? Explain with example.
- Explain the purpose for using Python modules.
- How many modules are there in Python?
- How to install and open a Python module?
- Where are Python modules stored?
While this is all about Python modules, we suggest you should also read about Packages in Python. Then, maybe you should switch to Packages vs Modules.