SoFunction
Updated on 2025-03-10

Path to create and add packages in Python ()

Create your own package in python, and in fact, you only need to create a folder. There is no need to have the __init__.py file in the folder, but if the __init__.py file exists in your folder, then when you import the package, python will immediately execute the contents in __init__.py and will only execute __init__.py. On the contrary, if you don't have this file in your folder (this package), you won't do anything when importing this package (in other words, your python will only load the name of the package, but then perform any other operations in it, you can check the default properties of the package). Therefore, in general, a package must have__init__.py, and often__init__.pyExecute import statements in the file, such as importing some packages in this folder, or encapsulating some classes and functions. The advantage of this is that as long as you import this package, you can use it__init__.pyAll packages loaded in the load.

1. Create a package

We have to do two things

  • Create a folder in the working directory and name itMy_package

  • In folderMy_packageCreate another one in__init__.pydocument

__init__.py

print('The package loaded successfully')

We can load import in the same level directory in the My_package folder (note that the working directory must be in the same level directory to load My_package. What should I do if it is not in the same level directory later)

import My_package

#OutputPackage loaded successfully

You can see that when the package is loaded (and a automatically generated in the My_package directory__pycache__folder), we wrote it in__init__.pyThe command line in it has been executed. Let's enrich it.__init__.pyAdd two functions to this content:

__init__.py

print('The package loaded successfully')

def fun1(a):
    print('Execution function 1:',a)
    return

def fun2(a):
    print('Execution function 2:',a)

Next we import this package and execute the functions inside.

import My_package
My_package.fun1('Start execution')
My_package.fun2('Start execution')

#OutputPackage loaded successfully
Execute functions1: Start execution
Execute functions2: Start execution

You can see that these functions have been executed.

Of course we can usefrom My_package import *This way to complete the above content

from My_package import *
fun1('Start execution')
fun2('Start execution')

#OutputPackage loaded successfully
Execute functions1: Start execution
Execute functions2: Start execution

You can see that the result is the same, so we have created our own package

2. Add modules to the package

Our common packages will have many, many other .py programs, not just__init__.py, because some content does not need to be executed when imported. Next, we add two modules to My_package. and.

print('Here is model1')

def fun1():
    print('Here is the first function of model1')
    return 

def fun2():
    print('Here is the second function of model1')
    return

print('Here is model2')

def fun1():
    print('Here is the first function of model2')
    return 

def fun2():
    print('Here is the second function of model2')
    return

After creating these two modules, we have four files under the My_package folder:

  • Folders__pycache__
  • document__init__.py
  • document
  • document

Below we import packages and modules in different ways and execute them.

Method 1:import My_package.Module name

import My_package.model1
import My_package.model2

#OutputPackage loaded successfully
here it ismodel1
here it ismodel2

My_package.model1.fun1()
My_package.model2.fun2()
#Outputhere it ismodel1The first function
here it ismodel2The second function

My_package.fun1('OK')

#OutputExecute functions1: OK

Can see__init__.pyIt is still executed, and when importing the package, the code in different models is also executed when importing it. It should be noted that using this import package name and module name method, a global variable My_package will appear to point to this package (we can view the properties of this global variable through dir(My_package). We can see that 'fun1', 'fun2', 'model1', and 'model2' all appear), so we can use the package name, module name, and function name to call functions of different models.

We can also execute it through the My_package. function name__init__.pyThe function in the package (this is because it is loaded using the import package name and module name, and Python will still execute the package__init__.py, and the generated object will be named My_package).

We can rename this long bundle of package names by adding as, this is the second method introduced.

Method 2:import My_package.model1 as xxx

import My_package.model1 as new_name1
import My_package.model2 as new_name2
#OutputPackage loaded successfully
here it ismodel1
here it ismodel2


new_name1.fun1() new_name2.fun2()
#Outputhere it ismodel1The first function
here it ismodel2The second function

You can see that we can use the new_name1 variable instead of My_package.model1. It should be noted that this way of renaming using as is that at this time, the global variable called My_package will not appear in Python to point to this package, so the program will not be able to find the variable My_package. Because python will assign the outermost model1 tonew_name1, without saving anything from My_package, although it was executedMy_packagemiddle__init__.py

Method 3: from My_package import model1

from My_package import model1
from My_package import model2
#OutputPackage loaded successfully
here it ismodel1
here it ismodel2

model1.fun1()
model2.fun2()
#Outputhere it ismodel1The first function
here it ismodel2The second function

My_package.fun1('OK')
#OutputNameError: name 'My_package' is not defined
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/tmp/ipykernel_9767/ in <module>
      2 from My_package import model2
      3 
----> 4 My_package.fun1('OK')
NameError: name 'My_package' is not defined

According to the import package method as the name implies, "import from My_package", at this time we can directly use model1. function name() to call the function. You can see that the same as the previous method, at this time, the global variable called My_package will not appear in python, although it has been executed.__init__.py, but python does not assign My_package to any variables, so it cannot be foundMy_package

Method 4:from My_package import *

from My_package import *
fun1('OK')
#OutputPackage loaded successfully
Execute functions1: OK

modle1.fun1()
#OutputNameError: name 'modle1' is not defined

Loading this way is actually equivalent to directly__init__.pyLoad directly into the workspace, can be used directly__init__.pyThe class or function in it does not need to add the My_package. function name. However, it should be noted that this kind of import is only imported into My_package__init__.py, no other model1 or model2 is imported, so the third line will report an error (and we can see that no model printing appears. In fact, this also indirectly shows that when only import packages are imported, python will only execute__init__.py)。

How should we call the functions in the model? Just use the following method.

from My_package.model1 import *
#OutputPackage loaded successfully
here it ismodel1

fun1()
fun2()
#Outputhere it ismodel1The first function
here it ismodel1The second function

In fact, it is not recommended to use this method, because if the same function name method appears in different models, the imported package will cover the former function name. For example, in these two examples in this article, the functions of model1 and model2 are both called fun1 and fun2. So if we import these two modules at the same time in this way, what problems will occur?

from My_package.model1 import *
from My_package.model2 import *
#OutputPackage loaded successfully
here it ismodel1
here it ismodel2

fun1()
fun2()
#Outputhere it ismodel2The first function
here it ismodel2The second function

You can see that after the first two sentences are executed, it shows that both packages have been imported. However, when we execute fun1 and fun2, the compiler recognizes the fun1 and fun2 of the later imported module model2, and the function of model2 is covered up. Therefore, it is not recommended that you use Method 4 as the method of importing packages.

3. Package path problem

When I first learned python, I was very curious, where is the import package? Where is the package I downloaded from pip install xxx? (Of course, you can search through the path). Why can I find these packages scattered everywhere in different places but import? In fact, these problems all come down to how import is imported into the package. In fact, when importing the package, python will search in some paths for folders (packages) or .py files with matching names.

You can run it by:

import sys

#Output['/home/g4/.vscode/extensions/-2021.3.684299474/pythonFiles/vscode_datascience_helpers/../.does-not-exist',
 '/home/g4/.vscode/extensions/-2021.3.684299474/pythonFiles',
 '/home/g4/.vscode/extensions/-2021.3.684299474/pythonFiles/lib/python',...]

(existubuntuDemonstrated on the system)

The current system environment variables (a list, each element is a path), when importing, Python will look for names that match in these paths. If it is not found, it will return our most common "ModuleNotFoundError: No module named 'kae'".

Through the discussion of this question, we can actually know that if the package we wrote ourselves wants to be imported, we need to write the path of the package into the environment variable (the working directory will be automatically added to the query scope of the import in the previous article). We don't need to modify the computer's environment variables, because it was just said that it was a list, so we can add the path where our package is located through the append method.

For demonstration, I put the My_package folder written in the previous section in the next level directory of the working directory.

import  My_package
#OutputModuleNotFoundError: No module named 'My_pacackge'
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
/tmp/ipykernel_31481/ in <module>
----> 1 import  My_pacackge
ModuleNotFoundError: No module named 'My_pacackge'

No surprise, an error was reported. Next we add the My_package folder directory to the system directory

import sys
('/home/g4/Desktop/project')
print('##############')
import My_package
#Output##############
Package loaded successfully

As you can see, the package is loading normally. For modules written by ourselves, we can use this method to load them.

4. Problem of importing packages with relative paths

To better distinguish, we will change the names of the two functions in it.

#No one answers the questions encountered during study?  The editor has created a Python learning exchange group: 531509025
print('Here is model2')

def model2_fun1():
    print('Here is the first function of model2')
    return 

def model2_fun1fun2():
    print('Here is the second function of model2')
    return

In the same package, if we want to use the function in it, we can import it normally by importing My_package.model2. However, there will be a problem. If one day, I change the name of the folder My_package, then the import My_package.model2 in this time will report an error. How to avoid this problem? We can import packages in a relative path. I will import My_package.model2 to import .model2.

Then no matter how the folder My_package is renamed, as long as it is under the same package, this line of code will be found correctly.

Next we will talk about the principle: the essence of python's relative path import package is to find the absolute path first and then import. He will follow model1__package__To find the variable, who is the package of model1 (in this case, My_package), then restore import .model2 to import My_package.model2, thereby completing the import.

After understanding this principle, I believe everyone will know why the import .model2 in it will report an error when I run it directly. Because when you run it directly, this file will be loaded into memory as main package. At this time, it does not belong to any package, so import .model2 will not be converted into import My_package.model2, and the correct model2 cannot be found, resulting in an error.

This is the article about creating packages and adding packages (()) in Python. For more related content on Python creation and adding packages, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!