Python module how to make

How to Write a Custom Module in Python

In my previous article for LearnPython.com, we learned about custom classes in Python. With Kateryna’s article on Python functions, you now have the required knowledge to implement your own custom module in Python.

If you are still wondering why you should learn Python in 2021, check out Rebecca’s excellent article on the topic.

In this article, we explore what a Python custom module is, and how to write a module in Python. Let’s get right into it.

What Is a Custom Module in Python?

A module is a Python program file composed of definitions or code you can leverage in other Python program files. They are the .py files written in Python.

You can write a Python module yourself. They can contain definitions of function, classes, and variables that can be used in other Python programs.

Why Write a Custom Module in Python?

Writing custom modules in Python is helpful for breaking down large parts of a program into smaller, more manageable, and organized files. It also increases the code reusability and is an excellent application of the DRY (Don’t Repeat Yourself) principle.

Читайте также:  Java приведение типов при наследовании

For example, instead of copying and pasting the functions we use into different programs over and over again, we can store them in a Python custom module and import them as needed.

How to Write a Custom Module in Python

Let’s run a quick example by writing a module called circle_area . It is saved as circle_area.py and contains a function to calculate the area of a circle:

# circle_area.py # Define a function def area_of_circle(r): pi = 3.14 area = pi * (r * r) return area

Then, we open another file called main.py in which we run our function, like this:

# main.py # Import the circle_area module import circle_area # Call the function print("Area of circle = %.6f" % circle_area.area_of_circle(7))

Because we are referencing a module, we need to call the function by referencing the module name in dot notation. For more information, you can see Kateryna’s article on Python functions.

When we run the main.py script in the console, we get the following output:

Area of circle = 153.860000

We have imported the whole module in the example above. Alternatively, we could have only imported the functions needed for our program. In this case, we would import just the area_of_circle() method as:

from circle_area import area_of_circle

We can also import a module by renaming it:

It can save typing time. Abbreviations often become standard practice in the industry; for example, the NumPy library is often imported as np.

We can also import all the definitions from a module with the asterisk (*) symbol, like so:

However, it is not a good programming practice, as it can lead to duplicate definitions and make the code less readable.

We can also define variables within the module and call them from our main script. For example, I have updated the previous circle_area.py module by adding a variable called coolpy :

# circle_area.py # Define a function def area_of_circle(r): pi = 3.14 area = pi * (r * r) return area # Define a variable coolpy = "LearnPython.com is cool!"

We then print it from our main.py file:

# Import the circle_area module import circle_area # Call the function print("Area of circle = %.6f" % circle_area.area_of_circle(7)) # Print the variable print(circle_area.coolpy)

This gives us the following output:

Area of circle = 153.860000 LearnPython.com is cool!

Building upon my previous article on how to write a custom class in Python, we can also add classes to our custom Python module. For clarity, I have created a new module saved as pypok.py , which contains the Pokemon class I used previously:

# pypok.py # Define a class class Pokemon: def __init__(self, power, level, names): self.power = power self.level = level self.names = names def __repr__(self): return (f'Pokemon(, ' f', ' f')') def total_damage(self): return self.damage(self.power, self.level) @staticmethod def damage(power, level): return (power * level * 2) / 50

We now add the class to main.py . For the script to run without error, I need to import my new pypok module.

# main.py # Import the circle_area and pypok modules import circle_area import pypok # Call the function print("Area of circle = %.6f" % circle_area.area_of_circle(7)) # Print the variable print(circle_area.coolpy) # Call the class squirtle = pypok.Pokemon(20, 8, "Squirtle") print("Squirtle inflicts", squirtle.total_damage(), "points of damage!")

Running our main.py script returns the following output:

Area of circle = 153.860000 LearnPython.com is cool! Squirtle inflicts 6.4 points of damage!

Once we have called the custom class previously defined, we can access the functions and attributes of the class within the main.py file’s namespace.

While we can write custom modules to define functions, we can also write them to implement code.

# circle_area.py # Define a function def area_of_circle(r): pi = 3.14 area = pi * (r * r) return area # Call the function inside the module print(area_of_circle(7))

We update the main.py script by deleting everything except the module import line:

# main.py # Import the circle_area module import circle_area

Now, we can run the script and get the following output:

As you can see, one line of import in our main.py file is enough to get the output. While this indeed works, you should avoid such solutions. Imports shouldn’t do anything more than letting Python know about new objects. After all, you don’t want to perform heavy calculations before they are needed.

It is better to keep the modules as general as possible to make them reusable and to avoid repeating ourselves. The project-specific variables should be kept in the general file, like main.py .

Write Custom Modules in Python!

I hope this article has given you a good understanding of how to write a module in Python. Do not hesitate to play with the snippets above and write your own modules.

Also, I encourage you to reflect on your programming practice. Which functions or classes do you use frequently? It can be a good practice to store them in your Python custom module to save time and make your code more readable and easier to maintain.

If you are looking for a list of online Python resources, Dorota has your back with her list of online resources for learning Python. Last but not least, if you want to learn more about all this and improve your Python skills, check our Python programming track. It gives you a roadmap to help you achieve your goals faster!

Источник

Creating a Python Module

So, you’ve been learning Python for quite a while now. As a beginner, it is common practice to have a one-file program that has all the code organized with the use of classes and functions.

But as you get more advanced, and your code gets more complex, you need to learn to use multiple files.

What Exactly is a Python Module?

A Python module is a Python file that contains classes, methods, or variables that you’d like to include in your application.

A common practice that you’ll observe among advanced Python applications is reusable functions or classes combined in a file, and then imported in other parts of the program.

Python Module Example 1

This is referred to as a Python module. This module can then be imported and the variables and functions can be reused multiple times without declaring or creating them every time.

How to Create a Python Module?

It’s simple, but we’ll break it down into small chunks for you to understand it and be able to apply it in real-world scenarios.

1. Create a File Containing a Method

We’ll first create a basic method that adds two numbers which it accepts as parameters.

name = "AskPython" def add(num1, num2): return num1 + num2

This is our module. The above code is simply a method that returns the sum of the two numbers that are passed to it. Save the above code as adder.py and we’ll move on to the next step.

2. Create the Main File to Import the Module

Our next step is to import custom python modules in our program. Now, this is exactly the same as importing any other module.

The only difference is that the module file is locally located instead of being in the system path.

import adder nums = adder.add(5, 10) print(nums)

Import Module Basics

In the above example, I’ve imported our “adder” file. You don’t need to add the “.py” extension while importing.

3. Importing Only One Function

Suppose in our module, we had multiple functions performing multiple tasks. But in the program that we are importing the module, we needed only one of those functions. Importing the entire module would be unnecessary.

In this case, we can make use of from and import together.

from adder import add nums = add(5, 10) print(nums)

Import Module Basics 1

As you can see, since we’re importing a specific function, Python allows us to use the function as if it was native to the file without having to reference it with the module name.

4. Using Variables From Our Module

You might have noticed the two variables in our module. We added those to demonstrate how variables can be directly imported from the module with their values intact.

import adder nums = adder.add(5, 10) print(nums) print(adder.name)

Module Import Variables

Importing Modules From Different Directory

You do not need to store the module in the same folder as your main file. That would become very inconvenient if there are a lot of files.

Also in case you’re importing a module to a different program, it will be difficult to use the module.

Instead, you can organize modules in folders, and still import them in the same manner as before. We’ll just have to make a small change to the import statement and everything else will run fine.

There are multiple ways we can import modules in our program which are not located in the root directory. Let’s start with the easy ones.

1. Import by Specifying Folder Name

The dot notation or from..import that we used above can be used to import modules that are located within a directory. Let’s place our “adder.py” module in a directory named modules.

Modules In Directory 1

import modules.adder as adder nums = adder.add(5, 10) print(nums) print(adder.name)

In this example, we renamed our module name from “modules.adder” to “adder” using as.

The reason for that is without renaming, we’ll have to specify “modules.adder.add(5,10)” and so on every time we need to call a function from the module.

We do not need to rename a module in the import statement. We can also create a variable later in the program that holds the name of the module and use the variable to call functions within the module.

This will work too, but declaring the new name right at the start of the program improves code readability making it easier for the next programmer who works on your piece of code.

Another way is to use from..import. This saves us from renaming the modules for use in the program. The only change I’ll need to make to my import command is to use from modules import adder

from modules import adder nums = adder.add(5, 10) print(nums) print(adder.name)

2. Append The Path to sys.path

When importing modules, Python starts by looking into the predefined paths first to find a module that matches the name. The first directory it looks into is the current directory, after which it moves to the other listed directories.

Let’s print out the sys.path and see what paths Python is looking into.

Sys Path In Python Linux

The above output is generated on a Linux computer. You will get a different list of paths if you’re using a Windows computer.

Since the sys.path is a Python list, we can append paths to it.

import sys sys.path.append("modules") import adder nums = adder.add(5, 10) print(nums) print(adder.name)

We imported the sys module and appended our “modules” directory to it. So any time you need to import a module in the modules directory within this program, you can simply specify the name and you should be good to start working.

3. Making a Module Available System-Wide

We printed out the sys.path in the above example. We know that Python will look into those directories by default irrespective of where your code is placed.

If we move our module to one of those directories, you will easily have access to the module from any program you create on your computer in the future.

Do note that when porting the program to a different system, you will need the module to be copied along. So for program-specific modules, it’s best to organize them in folders within the parent directory and import from there.

Conclusion

You should now be able to create your custom modules in Python and write multi-file programs. Remember, having code organized in multiple files with the use of classes is a far better option for code reusability.

Many functions that you need now, could be useful in a future application too and these individual modules that you’ve created would just need to be imported saving you hours of work in case of advanced applications.

Источник

Оцените статью