Python Advanced Fundamentals
Advanced
This page covers the advanced fundamentals of Python programming.
For Python intermediate fundamentals here.
It continues the previous intermediate tutorial in more details. Python advanced fundamentals encompass:
- create own modules
- built-in “dir()” function
Create own module
In Python, developers often need to store their own creations (e.g. functions, algorithms, or whole applications). The need for that is to reuse the code later when needed.
Store blocks of code is very easy and straightforward.
- The first step is to create a Python file (with the extension “.py“).
- Write the code, or copy if ready, and store inside the file.
- Save the file and the module is ready to use.
- Import the module or specific function and reuse.
The following is an example of storing a function in a module.
- The file’s name is “calculation.py“.
- The function name is “calculate()“
# simple calculation module def calculate(x, y): return x * 2 + (y * 4 + x)
The code above goes inside the Python file “calculation.py”. The file is saved and ready to use.
Now Python can import the module. The below code is on a separate file (e.g. “test.py“).
Please note that when importing the whole module, the specific function requires the module’s name as a prerequisite.
import calculation someCalc = calculation.calculate(7, 6) print(someCalc) # Output: 45
An alias (abbreviation) of the module can organise the code more efficiently.
import calculation as c someCalc = c.calculate(7, 6) print(someCalc) # Output: 45
When importing only a particular function, Python does not require declaration of the module’s name. In such cases, importing occurs through the keyword “from“.
from calculation import calculate someCalc = calculate(7, 6) print(someCalc) # Output: 45
Built-in “dir()” function
The programming language of Python offers a built-in function “dir()“.
The function “dir()” provides information regarding all features of an object (function, class, etc.). It can also list all functions in a module.
The example below continues with the module from above (calculation.py).
import calculation check = dir(calculation) print(check) # Output: ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'calculate']
The output shows several results. The eight in the front are super methods, which Python creates automatically. The last item in the list is the function (calculate) from the module (calculation).
Python can loop through the list in order to display the output better.
import calculation check = dir(calculation) for item in check: print(item)
# Output: __builtins__ __cached__ __doc__ __file__ __loader__ __name__ __package__ __spec__ calculate