#

Saturday, May 3, 2025

Working with Modules of Python for Network Engineers

Modules are Python files which ends with .py and Packages are directories which includes a collection of one or more Modules with a __init__.py file. A Library on the other hand can be a single module, a package, or a collection of Packages and Modules.

Standard Library

Following is the link to get info about all the Modules in Standard library.


Following example show the syntax of importing "time" module from Standard library and doing a simple work..







3rd Party Libraries

Let's see an example of a 3rd party library called "rich", 1st it needs to be installed..

pip3 install rich



This code makes the print text red, that's one thing the rich library do, styling..



Output will be;
If you noticed, the file I created is saved in /home/roshan/Python-Net-Eng/.venv/lib/python3.8/site-packages since this is the folder which the rich library is downloaded and installed. This is because when it tries to import there are certain locations it looks in including the current working directory. If it could not find it in those locations, script is not compiled. 

Following script shows which locations it looks to import the modules.




Import only a Module from a Library

Above example of importing rich library actually imported whole library, but in case if you need only a specific module to be imported from a library, following is the syntax.






In this case, the rich.print() is not working, instead we can use directly print().
But if we need to use the default print() function along with it, we can use an alias to the imported function like the following example.







Output will be like the following..





Let's do something manually to understand how it's working by creating a custom module.
Let's say we have a Module named "Modules.py" which I created with the following code in it, 







Following is the syntax to import only a one function inside above module,


No comments:

Post a Comment