Package init file python

Python — Packages

We organize a large number of files in different folders and subfolders based on some criteria, so that we can find and manage them easily. In the same way, a package in Python takes the concept of the modular approach to next logical level. As you know, a module can contain multiple objects, such as classes, functions, etc. A package can contain one or more relevant modules. Physically, a package is actually a folder containing one or more module files.

Let’s create a package named mypackage, using the following steps:

  • Create a new folder named D:\MyApp .
  • Inside MyApp , create a subfolder with the name ‘mypackage’.
  • Create an empty __init__.py file in the mypackage folder.
  • Using a Python-aware editor like IDLE, create modules greet.py and functions.py with the following code:
def SayHello(name): print("Hello ", name) 
def sum(x,y): return x+y def average(x,y): return (x+y)/2 def power(x,y): return x**y 

That’s it. We have created our package called mypackage. The following is a folder structure:

Package Folder Structure

Importing a Module from a Package

Now, to test our package, navigate the command prompt to the MyApp folder and invoke the Python prompt from there.

Import the functions module from the mypackage package and call its power() function.

>>> from mypackage import functions
>>> functions.power(3,2)
9

It is also possible to import specific functions from a module in the package.

>>> from mypackage.functions import sum
>>> sum(10,20)
30
>>> average(10,12)
Traceback (most recent call last):
File «», line 1, in
NameError: name ‘average’ is not defined

__init__.py

The package folder contains a special file called __init__.py , which stores the package’s content. It serves two purposes:

  1. The Python interpreter recognizes a folder as the package if it contains __init__.py file.
  2. __init__.py exposes specified resources from its modules to be imported.

An empty __init__.py file makes all functions from the above modules available when this package is imported. Note that __init__.py is essential for the folder to be recognized by Python as a package. You can optionally define functions from individual modules to be made available.

We shall also create another Python script in the MyApp folder and import the mypackage package in it. It should be at the same level of the package to be imported.

The __init__.py file is normally kept empty. However, it can also be used to choose specific functions from modules in the package folder and make them available for import. Modify __init__.py as below:

from .functions import average, power from .greet import SayHello 

The specified functions can now be imported in the interpreter session or another executable script.

Читайте также:  All about java variables

Create test.py in the MyApp folder to test mypackage.

from mypackage import power, average, SayHello SayHello() x=power(3,2) print("power(3,2) : ", x) 

Note that functions power() and SayHello() are imported from the package and not from their respective modules, as done earlier. The output of the above script is:

D:\MyApp>python test.py
Hello world
power(3,2) : 9

Install a Package Globally

Once a package is created, it can be installed for system-wide use by running the setup script. The script calls setup() function from the setuptools module.

Let’s install mypackage for system-wide use by running a setup script.

Save the following code as setup.py in the parent folder MyApp . The script calls the setup() function from the setuptools module. The setup() function takes various arguments such as name, version, author, list of dependencies, etc. The zip_safe argument defines whether the package is installed in compressed mode or regular mode.

from setuptools import setup setup(name='mypackage', version='0.1', description='Testing installation of Package', url='#', author='auth', author_email='[email protected]', license='MIT', packages=['mypackage'], zip_safe=False) 

Now execute the following command to install mypackage using the pip utility. Ensure that the command prompt is in the parent folder, in this case D:\MyApp .

D:\MyApp>pip install mypackage
Processing d:\MyApp
Installing collected packages: mypack
Running setup.py install for mypack . done
Successfully installed mypackage-0.1

Now mypackage is available for system-wide use and can be imported in any script or interpreter.

D:\>python
>>> import mypackage
>>>mypackage.average(10,20)
15.0
>>>mypackage.power(10,2)
100

You may also want to publish the package for public use. PyPI (stands for Python Package Index) is a repository of Python packages. Visit https://packaging.python.org/distributing to know more about the procedure of uploading a package to PyPI.

  • Compare strings in Python
  • Convert file data to list
  • Convert User Input to a Number
  • Convert String to Datetime in Python
  • How to call external commands in Python?
  • How to count the occurrences of a list item?
  • How to flatten list in Python?
  • How to merge dictionaries in Python?
  • How to pass value by reference in Python?
  • Remove duplicate items from list in Python
  • More Python articles

Источник

What is __init__.py? : A guide

While taking a look at sample Python projects, you may have seen this file, __init__.py. You may have wondered what it was, why it’s there if it’s empty, and how it works. This post will answer all of those questions!

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Читайте также:  Определить существует ли треугольник питон

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Here is an example file structure that includes __init__.py:

main_package/ __init__.py file1.py file2.py file3.py main.py

The main folder is our Python directory that we want to treat as if it were a Python package. To be treated as such, we have to include an __init__.py file that relays this information to the Python interpreter.

The rest of the files are just Python files that each have different information in it that we might want to use elsewhere. This could be a Class, a function, etc.

The main.py is where we are going to call for the functions that we have stored in main_package. You’ll see how this works in a minute, but first let’s take a look at the __init__.py file.

What is __init__.py?

The __init__.py file lets the Python interpreter know that a directory contains code for a Python module. An __init__.py file can be blank. Without one, you cannot import modules from another folder into your project.

The role of the __init__.py file is similar to the __init__ function in a Python class. The file essentially the constructor of your package or directory without it being called such. It sets up how packages or functions will be imported into your other files.

In its simplest case, the __init__.py file is an empty file. However, it is also used to set up imports, so they can be accessed elsewhere. There are three main ways to do that:

1. main_package/__init__.py and explicit imports :

from .file1 import file_1 # Where file_1 is the name of the function and .file1 is the name of the module/file from .file2 import file_2 from .file3 import file_3

We use relative imports to import each of the files into __init__.py. Inside these files are functions that are unique to each file.

In main.py, we can now access these functions by creating an import statement at the top of the file using explicit import statements:

from main_package import file_1, file_2, file_3 # This imports only what you need file_1() # This is my file 1! file_2() # And this is file 2! file_3() # Finally, here is file 3!

This tells us exactly which modules we are using out of main_package.

2. main_package/__init__.py and standard import:

import main_package # This imports the entire package main_package.file_1() # This is my file 1! main_package.file_2() # And this is file 2! main_package.file_3() # Finally, here is file 3!

The only difference between this one and the previous one is that the former imports only what we need (file_1, file_2, file_3). The other imports the module – so we use dot notation to access the function names.

Читайте также:  Python сколько раз встречается символ

3. main_package/__init__.py and wild card import:

In __init__.py, set an __all__ variable to a list of the modules/files in the package. This will help the interpreter figure out what’s to be considered when we use the wild card import statement in the main.py. Take notice that the all variable is surrounded by two underscores on either side.

__all__ = ["file1", "file2", "file3"]

In main.py we’ll use a generic import statement and use dot notation to access the function:

from main_package import * file1.file_1() #This is my file 1! file2.file_2() #And this is file 2! file3.file_3() #Finally, here is file 3!

The all variable serves to tell the wild card, *, which modules/files are to be included in that import. When we read from main_package import *, we should actually see it as from main_package import file1, file2, file3. Then we use dot notation to access the function name, as you can see above.

Importing Files Without an __init__.py File

If you want to import a file from another directory, that directory must contain a Python __init__.py file. Consider this example:

This statement imports a module called “create” from the “cakes” folder. Our cakes folder would need to have these two files for our code to work:

cakes/create.py cakes/__init__.py

The first file is our module. The second file tells Python that our directory contains Python modules. We could also import our code like this:

We could not use either of these import statements without an __init__.py file present.

To learn more about importing modules, check out our Python import statement guide.

Conclusion

That’s the __init__.py file in Python! How you use it in your project is very much up to how you would like to use imports.

Including an __init__.py file as part of your setup does make your code to be more Pythonic. This is because the structure of your code is clearer. Writing more Pythonic code is a big goal among software developers.

Here’s a repl with the Python code from this article. Use it to help visualize how the structure works and experiment with your own code!

For advice on top Python courses and online resources, check out our complete How to Learn Python guide.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Источник

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