Python init file example

The ‘__init__.py’ File: What Is It? How to Use It? (Complete Guide)

Typically, __init__.py is empty, but it can be used to configure the package or set the __all__ variable, which controls what symbols are imported when someone uses from package import * .

Can __init__.py Be Empty?

It is not required to have any content in order for the directory it is in to be treated as a package. It is only used to initialize the package when it is imported, and the contents of the file are executed as part of the import process.

If you don’t need to perform any initialization for your package, then you can leave __init__.py empty.

Do All Python Packages Require __init__.py File?

All Python packages need an __init__.py file before Python 3.3. Python versions of 3.3 or above no longer require the __init__.py file to define a package.

This file is used to indicate that the directory it is in should be treated as a package, and it is required for the package to be importable. Without an __init__.py file, the directory it is in cannot be treated as a package, and any attempt to import the package will fail.

Читайте также:  Perl html to xml

What Does __init__.py Do?

There are several things you can do with an __init__.py file in Python. Here are a few examples:

  • You can use __init__.py to configure the package when it is imported. For example, you can set variables or perform other initialization tasks that are needed for your package to work correctly.
  • You can use __init__.py to define which symbols should be imported when someone uses from package import * . This is done by setting the __all__ variable, which is a list of strings containing the names of the symbols that should be imported.
  • You can use __init__.py to define submodules or sub-packages within your package. This is done by creating subdirectories within your package and placing __init__.py files in those directories as well. This allows you to organize your package into logical units and makes it easier to use and maintain.
  • You can use __init__.py to define the package’s API, which is the set of functions, classes, and other symbols that are intended for public use. This can help users of your package understand what is available for them to use and how to use it.
  • You can use __init__.py to define custom import hooks or other custom behavior for your package. This can be useful for advanced use cases, such as implementing support for alternative module syntax or customizing the way your package is imported.

The __init__.py Is Not Required in Python 3.3+

In Python 3.3 and later versions, the __init__.py file is no longer required for defining a package. This is because the importlib module, which is the core of the import system, has been updated to automatically detect packages without the need for an __init__.py file. This means that you can create a package simply by creating a directory and placing your module files in it, without needing to create an __init__.py file.

Читайте также:  Hashcode java что делает

Create Package-Level Variables

You can use the __init__.py file to define variables at the package level.

The __init__.py file is executed when a package is imported, so any variables that are defined in this file will be available to all the modules in the package.

For example, you could define a variable named FOO in the __init__.py file in your package called my_pagage :

Then, any module in the package can access the value of FOO using the dot notation, like this:

import my_package print(my_package.FOO) # Outputs "Hello world"

Notice that the __init__.py file is executed only when the package is imported, so if you change the value of a variable defined in this file, you will need to re-import the package for the changes to take effect.

Summary

Today you learned what is the __init__.py file in Python.

The __init__.py file is used to indicate that the directory it is in should be treated as a Python package. This file is typically empty, but it can be used to perform initialization tasks for the package, such as setting variables or defining submodules.

The __init__.py file is required for the package to be importable, and it is used by the import system to find and load the package when it is imported.

Thanks for reading. Happy coding!

Источник

Package Initialization

Chris Bailey

In this lesson, you’ll learn about package initialization. If a file named __init__.py is present in a package directory, it is invoked when the package or a module in the package is imported. You can use this to execute package initialization code, for example for the initialization of package-level data.

Consider the following __init__.py file:

print(f'Invoking __init__.py for __name__>') alist = ['spam', 'bacon', 'eggs'] 

Add this file to the pkg directory from the above example:

Illustration of hierarchical file structure of Python packages

Now, when the package is imported, the global list alist is initialized:

>>> import pkg Invoking __init__.py for pkg >>> pkg.alist ['spam', 'bacon', 'eggs'] >>> pkg.mod1 Traceback (most recent call last): File "", line 1, in pkg.mod1 AttributeError: module 'pkg' has no attribute 'mod1' 

A module in the package can access the global by importing it in turn:

def load_data(): print('loading data using mod1.load_data()') from pkg import alist print(f'This is from pkg - alist>') class Customer: pass 
>>> from pkg import mod1 Invoking __init__.py for pkg >>> mod1.load_data() loading data using mod1.load_data() This is from pkg - ['spam', 'bacon', 'eggs'] 

Revert mod1.py to the previous version by changing load_data() to no longer use the import from pkg :

def load_data(): print('loading data using mod1.load_data()') class Customer: pass 

You can also use __init__.py to effect automatic importing of modules from a package. For example, earlier you saw that the statement import pkg only places the name pkg in the caller’s local symbol table and doesn’t import any modules. Let’s say that __init__.py in the pkg directory contains the following:

print(f'Invoking __init__.py for __name__>') import pkg.mod1, pkg.mod2 

Then, when you execute import pkg , modules mod1 and mod2 would be imported automatically:

>>> import pkg Invoking __init__.py for pkg >>> pkg.mod1.load_data() loading data using mod1.load_data() >>> x = pkg.mod2.Location() >>> x 

Note: Much of the Python documentation states that an __init__.py file must be present in the package directory when creating a package. This was once true. It used to be that the very presence of __init__.py signified to Python that a package was being defined. The file could contain initialization code or even be empty, but it had to be present.

Starting with Python 3.3, Implicit Namespace Packages were introduced. These allow for the creation of a package without any __init__.py file. Of course, it can still be present if package initialization is needed. But it is no longer required.

Источник

How to create a Python Package with __init__.py

Banner

A Python package is simply an organized collection of python modules. A python module is simply a single python file.

Why would I want to create a package using __init__.py ?

Creating a package with __init__.py is all about making it easier to develop larger Python projects.

It provides a mechanism for you to group separate python scripts into a single importable module.

Let’s run through some examples

The best way to understand why you would use __init__.py and to learn how to use it to create a package is to run through some quick examples! The best way to learn is by doing!

The code in this tutorial should work for Python 2 or 3. Just remember, if you are using 2 then you will need to use the from __future__ import print_function functionality.

Say we have three modules we have created:

someFolder |-- stringLength.py |-- stringToUpper.py `-- stringToLower.py

Remember a module is just another name for any single python file

For our example, the content of these files is the following:

# stringLength.py def stringLength(inStr): return len(inStr) 
# stringToUpper.py def stringToUpper(inStr): return inStr.upper() 
# stringToLower.py def stringToLower(inStr): return inStr.lower() 

Obviously, these functions are useless, but it helps to serve as a model for the basic concept that we have some python modules that we have already written that are somehow related.

So, without creating a package and using __init__.py , how do we use the functions in these files?

Well, we can only import these files if they are in the current directory that whatever script we are running is running from.

Well, we can use these files in a new Python script but with one key caveat:

To illustrate that, let’s create a file called example1.py that leverages our modules:

# example1.py import stringLength import stringToLower import stringToUpper some_string = "Hello, Universe!" print(stringLength.stringLength(some_string)) print(stringToLower.stringToLower(some_string)) print(stringToUpper.stringToUpper(some_string)) 

Adding a blank __init__.py

What if we wanted to seperate these scripts into a folder in order to keep them more organized?

Well, that is where the __init__.py file comes into play.

First, lets move our scripts into a new subfolder and call it: string_func . Then create an empty file in that folder called __init__.py

Here is our new file/folder structure:

someFolder |-- string_func | |-- __init__.py | |-- stringToUpper.py | |-- stringToLower.py | `-- strengthLength.py `-- example1.py

So, now let’s test out exactly what __init__.py allows us to do:

Let’s make a new example2.py file.

# example2.py import string_func.stringLength import string_func.stringToLower import string_func.stringToUpper some_string = "Hello, Universe!" print(string_func.stringLength.stringLength(some_string)) print(string_func.stringToLower.stringToLower(some_string)) print(string_func.stringToUpper.stringToUpper(some_string)) 

So, now we can access our string functions in this manner. This is great, because they are all in a seperate folder, but the syntax is definitely not very succinct. Let’s see if we can clean things up a bit by editing our __init__.py file.

Adding imports to init.py

Open your __init__.py file and make the following changes:

# __init__.py from .stringLength import stringLength from .stringToLower import stringToLower from .stringToUpper import stringToUpper 

And so with that in our __init__.py we can now shorten our code to:

# example3.py import string_func some_string = "Hello, Universe!" print(string_func.stringLength(some_string)) print(string_func.stringToLower(some_string)) print(string_func.stringToUpper(some_string)) 

Now the syntax is a lot shorter and you can see that string_func is behaving like its own module.

So, that is basically what __init__.py does! It allows you to treat a directory as if it was a python module. Then you can further define imports inside your __init__.py file to make imports more succinct, or you can just leave the file blank.

Debugging import Issues

There are basically 3 tips I have for debugging import issues:

  1. Use the interactive interpreter (The REPL) to import the modules and see if you are getting what you expect.
  2. Start your script with python -v -m my_scriptname.py and then check the output to see exactly where your modules are getting imported from.
  3. Use Pycharm. Pycharm’s fantastic introspection abilities mean that you will immeadiately know whether or not your module is being properly imported as it will indicate an error if not. It will sometimes also suggest the proper correction. The community edition is free and if you’re a student you can get a free subscription to ALL of their products!

For more information about python modules and packages you can see check the python documentation on it.

You can also check out this great Talk Python To Me podcast with David Beazley where he discusses the subject, as well as David’s talk on the same subject.

As usual, feel free to contact me if you come across any errors in this post!

Источник

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