Python Module and Tricks By albro

in Programming & Dev3 years ago

Python Module and tricks

In implementing a real, medium or large project, there is a lot of code in our program. Modules in Python help us organize this code. Each module is a Python file that contains code. By importing these, we can use its codes in other files.

Suppose we have written user login for a project. Now we want to implement exactly the same system for another project. That means we have to write similar codes and functions!

The solution that comes to our mind is that we use the previous codes in the new files. I'm not saying this method is bad! But managing changes and organizing these codes becomes a bit difficult.

With the help of modules in Python, in addition to being able to organize our code, we can use frequently used code in several projects. By organizing, I mean writing program codes in specific files and using these files in combination.

In this post, I'll first tell you how to create a module in Python. Then I'll explain how to call and use the modules. Finally, where to use additional discussions such as these modules.

Finally, I will discuss additional considerations, such as where to use these modules.

Creating a Python module

Until this post from the series of Python posts, I used to write the codes in a file with .py format. I run this file in the command line or IDEs according to my needs.

Each .py file is a module in Python! That means I can call and use its codes in another file. Suppose I wrote the greetings() function to print a simple message in myprint.py file:

def greetings(name):
    print("Hello {name}, Welcome to Hive Blockchain!")

Now I have a module called myprint that I can use in other files. 🙂

Before we use the module, it is better to know what kind of code is included in the Python module? We can put almost any kind of code in modules!

  • Python functions that we have defined ourselves.
  • Various variables such as dictionary, Python string or lists
  • Even codes in the main scope of the module! (Of course, the executable code in the module may cause problems for us, which we will review in the final section.)

Import the Python module

Now we want to call this function in the app.py file which is next to myprint.py. For this, we must first import the module into the app file. Simply put, we tell Python that:

Copy the codes of this module in the current file! Because we want to use them.

To use the module, we use the import statement in Python. We can use this statement in 3 different structures, which I will explain below.

Python Modules Example Folder

import module statemet in Python

The general structure of this command is similar to the following:

import module1 [,module2 [,module3 ...]]

To use the myprint module, I write the following statement at the beginning of the app.py file:

import myprint

If we want to import several modules at the same time, we use a comma (,) between the names. For example, in the following statement, in addition to our own module, I have called 2 mathematical calculation modules and Python random functions:

import myprint, math, random

When we want to call the greetings() function in the app file, we must add the "module name" along with a dot (.) to the beginning of the function name. Something like the following:

import myprint
myprint.greetings("albro")

For example, to generate a random number between 0 and 20, we can do the following:

import random
rnd = random.randint(0, 20)

from import statement

I create a file called utils.py with the following codes.

# utils.py
def calc(x):
    return (x**2)*(x+1)
class Person():
    def __init__(self, name):
        self.name = name
users = ['albro', 'xeldal', 'minnowbooster']

If we call this module in another file (eg app.py), we will have access to all its functions, classes and variables:

# app.py
import utils
print( utils.calc(5) )
p1 = utils.Person('grindle')
utils.users.append('leo.voter')

Sometimes we don't need all the code in a module. For example, we just want to use the calc() function. Therefore, importing other codes is unnecessary and somewhat unprofessional!

To call only one or more items from the module, the from ... import ... structure is used.

# import single thing from madule
from utils import calc
# import multiple things
from utils import calc, users

simply! 🙂

In this case, when we want to call the function or variable, there is no need to write the name of the module at the beginning of them. That is, I can use the imported function and list as follows:

from utils import calc, users
print( calc(5) )

If we want to call all functions and variables in the module in this way, an asterisk (*) is used instead of naming all functions:

from utils import *

In this way, the whole module is included in the code and we don't need to write the module name to use the functions.

Import with rename in Python

Sometimes we need to change the name of a module or things we have imported from it. This issue can have two general reasons:

  • Let's shorten its name or call it by any desired name.
  • This module or its functions have the same name as our codes.

To change the name of the module in Python, we use the as keyword when calling. This method is also known as "alias".

import random as rnd

In the code above, I have included the random module with the alias rnd in the code. From now on, we should use rnd instead of random:

rnd.randint(0, 20)

We can also use this for functions that are imported; Like the following code:

from utils import calc as calculate
print( calculate(5) )

tricks

At the beginning of the post, I briefly reviewed the use of modules with you. Personally, I consider 4 general uses for modules in Python:

  1. Organize code by converting a set of related functions into a module
  2. The possibility of reusing some code (and making our program modular)
  3. With the help of modularization, we can use other people's codes (or our own previous codes).
  4. We may publish or make these modules available to others.

Search path for python modules

When the import statement is used, the Python interpreter checks several paths to call the desired module. First, it searches in the list of built-in modules that exist with the installation of Python, and if nothing is found, it looks for the desired module in other paths.

In general, the following routes are checked in order:

  • Built-in modules
  • Current folder
  • Folders that are in the operating system's local PYTHONPATH variable. (The one defined in the Python path setting.)
  • Several folders in the Python installation path

dir function to check the module

The dir() function takes the module we imported as input and gives us a list of functions and variables inside it. This function is usually used for module checking or Python error handling tasks.

import utils
print( dir(utils) )
# output:
# ['Person', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'calc', 'users']
Sort:  

https://leofinance.io/threads/view/albro/re-leothreads-dow66w4o
The rewards earned on this comment will go directly to the people ( albro ) sharing the post on LeoThreads,LikeTu,dBuzz.

Congratulations @albro! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You received more than 100 HP as payout for your posts, comments and curation.
Your next payout target is 250 HP.
The unit is Hive Power equivalent because post and comment rewards can be split into HP and HBD

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Check out our last posts:

LEO Power Up Day - May 15, 2023
The Hive Gamification Proposal
Support the HiveBuzz project. Vote for our proposal!

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

Congratulations!


You have obtained a vote from CHESS BROTHERS PROJECT

✅ Good job. Your post has been appreciated and has received support from CHESS BROTHERS ♔ 💪


♟ We invite you to use our hashtag #chessbrothers and learn more about us.

♟♟ You can also reach us on our Discord server and promote your posts there.

♟♟♟ Consider joining our curation trail so we work as a team and you get rewards automatically.

♞♟ Check out our @chessbrotherspro account to learn about the curation process carried out daily by our team.


🏅 If you want to earn profits with your HP delegation and support our project, we invite you to join the Master Investor plan. Here you can learn how to do it.


Kindly

The CHESS BROTHERS team