Файл init python что это
Перейти к содержимому

Файл init python что это

  • автор:

6. Modules¶

If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.

To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__ . For instance, use your favorite text editor to create a file called fibo.py in the current directory with the following contents:

Now enter the Python interpreter and import this module with the following command:

This does not add the names of the functions defined in fibo directly to the current namespace (see Python Scopes and Namespaces for more details); it only adds the module name fibo there. Using the module name you can access the functions:

If you intend to use a function often you can assign it to a local name:

6.1. More on Modules¶

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. 1 (They are also run if the file is executed as a script.)

Each module has its own private namespace, which is used as the global namespace by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname .

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names, if placed at the top level of a module (outside any functions or classes), are added to the module’s global namespace.

There is a variant of the import statement that imports names from a module directly into the importing module’s namespace. For example:

This does not introduce the module name from which the imports are taken in the local namespace (so in the example, fibo is not defined).

There is even a variant to import all names that a module defines:

This imports all names except those beginning with an underscore ( _ ). In most cases Python programmers do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined.

Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.

If the module name is followed by as , then the name following as is bound directly to the imported module.

This is effectively importing the module in the same way that import fibo will do, with the only difference of it being available as fib .

It can also be used when utilising from with similar effects:

For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use importlib.reload() , e.g. import importlib; importlib.reload(modulename) .

6.1.1. Executing modules as scripts¶

When you run a Python module with

the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__" . That means that by adding this code at the end of your module:

you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:

If the module is imported, the code is not run:

This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).

6.1.2. The Module Search Path¶

When a module named spam is imported, the interpreter first searches for a built-in module with that name. These module names are listed in sys.builtin_module_names . If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path . sys.path is initialized from these locations:

The directory containing the input script (or the current directory when no file is specified).

PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH ).

The installation-dependent default (by convention including a site-packages directory, handled by the site module).

On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed. In other words the directory containing the symlink is not added to the module search path.

After initialization, Python programs can modify sys.path . The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

6.1.3. “Compiled” Python files¶

To speed up loading modules, Python caches the compiled version of each module in the __pycache__ directory under the name module. version .pyc , where the version encodes the format of the compiled file; it generally contains the Python version number. For example, in CPython release 3.3 the compiled version of spam.py would be cached as __pycache__/spam.cpython-33.pyc . This naming convention allows compiled modules from different releases and different versions of Python to coexist.

Python checks the modification date of the source against the compiled version to see if it’s out of date and needs to be recompiled. This is a completely automatic process. Also, the compiled modules are platform-independent, so the same library can be shared among systems with different architectures.

Python does not check the cache in two circumstances. First, it always recompiles and does not store the result for the module that’s loaded directly from the command line. Second, it does not check the cache if there is no source module. To support a non-source (compiled only) distribution, the compiled module must be in the source directory, and there must not be a source module.

Some tips for experts:

You can use the -O or -OO switches on the Python command to reduce the size of a compiled module. The -O switch removes assert statements, the -OO switch removes both assert statements and __doc__ strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have an opt- tag and are usually smaller. Future releases may change the effects of optimization.

A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded.

The module compileall can create .pyc files for all modules in a directory.

There is more detail on this process, including a flow chart of the decisions, in PEP 3147.

6.2. Standard Modules¶

Python comes with a library of standard modules, described in a separate document, the Python Library Reference (“Library Reference” hereafter). Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. The set of such modules is a configuration option which also depends on the underlying platform. For example, the winreg module is only provided on Windows systems. One particular module deserves some attention: sys , which is built into every Python interpreter. The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts:

These two variables are only defined if the interpreter is in interactive mode.

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH , or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

6.3. The dir() Function¶

The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings:

Without arguments, dir() lists the names you have defined currently:

Note that it lists all types of names: variables, modules, functions, etc.

dir() does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module builtins :

6.4. Packages¶

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A . Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or Pillow from having to worry about each other’s module names.

Suppose you want to design a collection of modules (a “package”) for the uniform handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, for example: .wav , .aiff , .au ), so you may need to create and maintain a growing collection of modules for the conversion between the various file formats. There are also many different operations you might want to perform on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so in addition you will be writing a never-ending stream of modules to perform these operations. Here’s a possible structure for your package (expressed in terms of a hierarchical filesystem):

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Users of the package can import individual modules from the package, for example:

This loads the submodule sound.effects.echo . It must be referenced with its full name.

An alternative way of importing the submodule is:

This also loads the submodule echo , and makes it available without its package prefix, so it can be used as follows:

Yet another variation is to import the desired function or variable directly:

Again, this loads the submodule echo , but this makes its function echofilter() directly available:

Note that when using from package import item , the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.

Contrarily, when using syntax like import item.subitem.subsubitem , each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.

6.4.1. Importing * From a Package¶

Now what happens when the user writes from sound.effects import * ? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__ , it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package. For example, the file sound/effects/__init__.py could contain the following code:

This would mean that from sound.effects import * would import the three named submodules of the sound.effects package.

If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py ) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py . It also includes any submodules of the package that were explicitly loaded by previous import statements. Consider this code:

In this example, the echo and surround modules are imported in the current namespace because they are defined in the sound.effects package when the from. import statement is executed. (This also works when __all__ is defined.)

Although certain modules are designed to export only names that follow certain patterns when you use import * , it is still considered bad practice in production code.

Remember, there is nothing wrong with using from package import specific_submodule ! In fact, this is the recommended notation unless the importing module needs to use submodules with the same name from different packages.

6.4.2. Intra-package References¶

When packages are structured into subpackages (as with the sound package in the example), you can use absolute imports to refer to submodules of siblings packages. For example, if the module sound.filters.vocoder needs to use the echo module in the sound.effects package, it can use from sound.effects import echo .

You can also write relative imports, with the from module import name form of import statement. These imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use:

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__" , modules intended for use as the main module of a Python application must always use absolute imports.

6.4.3. Packages in Multiple Directories¶

Packages support one more special attribute, __path__ . This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.

While this feature is not often needed, it can be used to extend the set of modules found in a package.

In fact function definitions are also ‘statements’ that are ‘executed’; the execution of a module-level function definition adds the function name to the module’s global namespace.

Как работают импорты в Python

Обложка: Как работают импорты в Python

Порой бывает трудно правильно реализовать import с первого раза, особенно если мы хотим добиться правильной работы на плохо совместимых между собой версиях Python 2 и Python 3. Попытаемся разобраться, что из себя представляют импорты в Python и как написать решение, которое подойдёт под обе версии языка.

Содержание

Ключевые моменты

  • Выражения import производят поиск по списку путей в sys.path .
  • sys.path всегда включает в себя путь скрипта, запущенного из командной строки, и не зависит от текущей рабочей директории.
  • Импортирование пакета по сути равноценно импортированию __init__.py этого пакета.

Основные определения

  • Модуль: любой файл *.py . Имя модуля — имя этого файла.
  • Встроенный модуль: «модуль», который был написан на Си, скомпилирован и встроен в интерпретатор Python, и потому не имеет файла *.py .
  • Пакет: любая папка, которая содержит файл __init__.py . Имя пакета — имя папки.
    • С версии Python 3.3 любая папка (даже без __init__.py ) считается пакетом.

    Пример структуры директорий

    Обратите внимание, что в корневой папке test/ нет файла __init__.py .

    Что делает import

    При импорте модуля Python выполняет весь код в нём. При импорте пакета Python выполняет код в файле пакета __init__.py , если такой имеется. Все объекты, определённые в модуле или __init__.py , становятся доступны импортирующему.

    Встроенные функции Python: какие нужно знать и на какие не стоит тратить время

    Основы import и sys.path

    Вот как оператор import производит поиск нужного модуля или пакета согласно документации Python:

    • директории, содержащей исходный скрипт (или текущей директории, если файл не указан);
    • директории по умолчанию, которая зависит от дистрибутива Python;
    • PYTHONPATH (список имён директорий; имеет синтаксис, аналогичный переменной окружения PATH ).

    Технически документация не совсем полна. Интерпретатор будет искать не только файл (модуль) spam.py , но и папку (пакет) spam .

    Обратите внимание, что Python сначала производит поиск среди встроенных модулей — тех, которые встроены непосредственно в интерпретатор. Список встроенных модулей зависит от дистрибутива Python, а найти этот список можно в sys.builtin_module_names (Python 2 и Python 3). Обычно в дистрибутивах есть модули sys (всегда включён в дистрибутив), math , itertools , time и прочие.

    В отличие от встроенных модулей, которые при поиске проверяются первыми, остальные (не встроенные) модули стандартной библиотеки проверяются после директории запущенного скрипта. Это приводит к сбивающему с толку поведению: возможно «заменить» некоторые, но не все модули стандартной библиотеки. Допустим, модуль math является встроенным модулем, а random — нет. Таким образом, import math в start.py импортирует модуль из стандартной библиотеки, а не наш файл math.py из той же директории. В то же время, import random в start.py импортирует наш файл random.py .

    Кроме того, импорты в Python регистрозависимы: import Spam и import spam — разные вещи.

    Функцию pkgutil.iter_modules() (Python 2 и Python 3) можно использовать, чтобы получить список всех модулей, которые можно импортировать из заданного пути:

    Чуть подробнее о sys.path

    Чтобы увидеть содержимое sys.path , запустите этот код:

    Документация Python описывает sys.path так:

    Список строк, указывающих пути для поиска модулей. Инициализируется из переменной окружения PYTHONPATH и директории по умолчанию, которая зависит от дистрибутива Python.

    При запуске программы после инициализации первым элементом этого списка, path[0] , будет директория, содержащая скрипт, который был использован для вызова интерпретатора Python. Если директория скрипта недоступна (например, если интерпретатор был вызван в интерактивном режиме или скрипт считывается из стандартного ввода), то path[0] является пустой строкой. Из-за этого Python сначала ищет модули в текущей директории. Обратите внимание, что директория скрипта вставляется перед путями, взятыми из PYTHONPATH .

    Источник: Python 2 и Python 3

    Документация к интерфейсу командной строки Python добавляет информацию о запуске скриптов из командной строки. В частности, при запуске python <script>.py .

    Если имя скрипта ссылается непосредственно на Python-файл, то директория, содержащая этот файл, добавляется в начало sys.path , а файл выполняется как модуль main .

    Источник: Python 2 и Python 3

    Итак, повторим порядок, согласно которому Python ищет импортируемые модули:

    1. Модули стандартной библиотеки (например, math , os ).
    2. Модули или пакеты, указанные в sys.path :
        1. Если интерпретатор Python запущен в интерактивном режиме:
          • sys.path[0] — пустая строка » . Это значит, что Python будет искать в текущей рабочей директории, из которой вы запустили интерпретатор. В Unix-системах эту директорию можно узнать с помощью команды pwd .

        Если мы запускаем скрипт командой python <script>.py :

        • sys.path[0] — это путь к <script>.py .

        Обратите внимание, что при запуске скрипта для sys.path важна не директория, в которой вы находитесь, а путь к самому скрипту. Например, если в командной строке мы находимся в test/folder и запускаем команду python ./packA/subA/subA1.py , то sys.path будет включать в себя test/packA/subA/ , но не test/ .

        Кроме того, sys.path общий для всех импортируемых модулей. Допустим, мы вызвали python start.py . Пусть start.py импортирует packA.a1 , а a1.py выводит на экран sys.path . В таком случае sys.path будет включать test/ (путь к start.py ), но не test/packA (путь к a1.py ). Это значит, что a1.py может вызвать import other , так как other.py находится в test/ .

        Всё о __init__.py

        У файла __init__.py есть две функции:

        1. Превратить папку со скриптами в импортируемый пакет модулей (до Python 3.3).
        2. Выполнить код инициализации пакета.

        Превращение папки со скриптами в импортируемый пакет модулей

        Чтобы импортировать модуль (или пакет) из директории, которая находится не в директории нашего скрипта (или не в директории, из которой мы запускаем интерактивный интерпретатор), этот модуль должен быть в пакете.

        Как было сказано ранее, любая директория, содержащая файл __init__.py , является пакетом. Например, при работе с Python 2.7 start.py может импортировать пакет packA , но не packB , так как в директории test/packB/ нет файла __init__.py .

        Это не относится к Python 3.3 и выше благодаря появлению неявных пакетов пространств имён. Проще говоря, в Python 3.3+ все папки считаются пакетами, поэтому пустые файлы __init__.py больше не нужны.

        Допустим, packB — пакет пространства имён, так как в нём нет __init__.py . Если запустить интерактивную оболочку Python 3.6 в директории test/ , то мы увидим следующее:

        Выполнение кода инициализации пакета

        В момент, когда пакет или один из его модулей импортируется в первый раз, Python выполняет __init__.py в корне пакета, если такой файл существует. Все объекты и функции, определённые в __init__.py , считаются частью пространства имён пакета.

        Рассмотрим следующий пример:

        Вывод после запуска python start.py :

        Примечание Если a1.py вызовет import a2 , и мы запустим python a1.py , то test/packA/__init__.py не будет вызван, несмотря на то, что a2 вроде бы является частью пакета packA . Это связано с тем, что когда Python выполняет скрипт (в данном случае a1.py ), содержащая его папка не считается пакетом.

        Использование объектов из импортированного модуля или пакета

        Есть 4 разных вида импортов:

        1. import <пакет>
        2. import <модуль>
        3. from <пакет> import <модуль или подпакет или объект>
        4. from <модуль> import <объект>

        Пусть X — имя того, что идёт после import :

        • Если X — имя модуля или пакета, то для того, чтобы использовать объекты, определённые в X , придётся писать X.объект .
        • Если X — имя переменной, то её можно использовать напрямую.
        • Если X — имя функции, то её можно вызвать с помощью X() .

        Опционально после любого выражения import X можно добавить as Y . Это переименует X в Y в пределах скрипта. Учтите, что имя X с этого момента становится недействительным. Частым примером такой конструкции является import numpy as np .

        Аргументом для import может быть как одно имя, так и их список. Каждое из имён можно переименовать с помощью as . Например, следующее выражение будет действительно в start.py : import packA as pA, packA.a1, packA.subA.sa1 as sa1 .

        Пример: нужно в start.py импортировать функцию helloWorld() из sa1.py .

        • Решение 1: from packA.subA.sa1 import helloWorld . Мы можем вызвать функцию напрямую по имени: x = helloWorld() .
        • Решение 2: from packA.subA import sa1 или то же самое import packA.subA.sa1 as sa1 . Для использования функции нам нужно добавить перед её именем имя модуля: x = sa1.helloWorld() . Иногда такой подход предпочтительнее первого, так как становится ясно, из какого модуля взялась та или иная функция.
        • Решение 3: import packA.subA.sa1 . Для использования функции перед её именем нужно добавить полный путь: x = packA.subA.sa1.helloWorld() .

        Используем dir() для исследования содержимого импортированного модуля

        После импортирования модуля можно использовать функцию dir() для получения списка доступных в модуле имён. Допустим, мы импортируем sa1 . Если в sa1.py есть функция helloWorld() , то dir(sa1) будет включать helloWorld :

        Импортирование пакетов

        Импортирование пакета по сути равноценно импортированию его __init__.py . Вот как Python на самом деле видит пакет:

        После импорта становятся доступны только те объекты, что определены в __init__.py пакета. Поскольку в packB нет такого файла, от import packB (в Python 3.3.+) будет мало толку, так как никакие объекты из этого пакета не становятся доступны. Последующий вызов модуля packB.b1 приведёт к ошибке, так как он ещё не был импортирован.

        Абсолютный и относительный импорт

        При абсолютном импорте используется полный путь (от начала корневой папки проекта) к желаемому модулю.

        При относительном импорте используется относительный путь (начиная с пути текущего модуля) к желаемому модулю. Есть два типа относительных импортов:

        1. При явном импорте используется формат from .<модуль/пакет> import X , где символы точки . показывают, на сколько директорий «вверх» нужно подняться. Одна точка . показывает текущую директорию, две точки .. — на одну директорию выше и т. д.
        2. Неявный относительный импорт пишется так, как если бы текущая директория была частью sys.path . Такой тип импортов поддерживается только в Python 2.

        В документации Python об относительных импортах в Python 3 написано следующее:

        Единственный приемлемый синтаксис для относительных импортов — from .[модуль] import [имя] . Все импорты, которые начинаются не с точки . , считаются абсолютными.

        Источник: What’s New in Python 3.0

        В качестве примера допустим, что мы запускаем start.py , который импортирует a1 , который импортирует other , a2 и sa1 . Тогда импорты в a1.py будут выглядеть следующим образом:

        Явные относительные импорты:

        Неявные относительные импорты (не поддерживаются в Python 3):

        Учтите, что в относительных импортах с помощью точек . можно дойти только до директории, содержащей запущенный из командной строки скрипт (не включительно). Таким образом, from .. import other не сработает в a1.py . В результате мы получим ошибку ValueError: attempted relative import beyond top-level package .

        Как правило, абсолютные импорты предпочтительнее относительных. Они позволяют избежать путаницы между явными и неявными импортами. Кроме того, любой скрипт с явными относительными импортами нельзя запустить напрямую:

        Имейте в виду, что относительные импорты основаны на имени текущего модуля. Так как имя главного модуля всегда «__main__» , модули, которые должны использоваться как главный модуль приложения, должны всегда использовать абсолютные импорты.

        Источник: Python 2 и Python 3

        Примеры

        Пример 1: sys.path известен заранее

        Если вы собираетесь вызывать только python start.py или python other.py , то прописать импорты всем модулям не составит труда. В данном случае sys.path всегда будет включать папку test/ . Таким образом, все импорты можно писать относительно этой папки.

        Пример: файлу в проекте test нужно импортировать функцию helloWorld() из sa1.py .

        Решение: from packA.subA.sa1 import helloWorld (или любой другой эквивалентный синтаксис импорта).

        Пример 2: sys.path мог измениться

        Зачастую нам требуется как запускать скрипт напрямую из командной строки, так и импортировать его как модуль в другом скрипте. Как вы увидите далее, здесь могут возникнуть проблемы, особенно в Python 3.

        Пример: пусть start.py нужно импортировать a2 , которому нужно импортировать sa2 . Предположим, что start.py всегда запускается напрямую, а не импортируется. Также мы хотим иметь возможность запускать a2 напрямую.

        Звучит просто, не так ли? Нам всего лишь нужно выполнить два импорта: один в start.py и другой в a2.py .

        Проблема: это один из тех случаев, когда sys.path меняется. Когда мы выполняем start.py , sys.path содержит test/ , а при выполнении a2.py sys.path содержит test/packA/ .

        С импортом в start.py нет никаких проблем. Так как этот модуль всегда запускается напрямую, мы знаем, что при его выполнении в sys.path всегда будет test/ . Тогда импортировать a2 можно просто с помощью import packA.a2 .

        С импортом в a2.py немного сложнее. Когда мы запускаем start.py напрямую, sys.path содержит test/ , поэтому в a2.py импорт будет выглядеть как from packA.subA import sa2 . Однако если запустить a2.py напрямую, то в sys.path уже будет test/packA/ . Теперь импорт вызовет ошибку, так как packA не является папкой внутри test/packA/ .

        Вместо этого мы могли бы попробовать from subA import sa2 . Это решает проблему при запуске a2.py напрямую, однако теперь создаёт проблему при запуске start.py . В Python 3 это приведёт к ошибке, потому что subA не находится в sys.path (в Python 2 это не вызовет проблемы из-за поддержки неявных относительных импортов).

        Запускаем from packA.subA import sa2 from subA import sa2
        start.py Нет проблем В Py2 нет проблем, в Py3 ошибка ( subA не в test/ )
        a2.py Ошибка ( packA не в test/packA/ ) Нет проблем

        Использование относительного импорта from .subA import sa2 будет иметь тот же эффект, что и from packA.subA import sa2 .

        Вряд ли для этой проблемы есть чистое решение, поэтому вот несколько обходных путей:

        1. Использовать абсолютные импорты относительно директории test/ (т. е. средняя колонка в таблице выше). Это гарантирует, что запуск start.py напрямую всегда сработает. Чтобы запустить a2.py напрямую, запустите его как импортируемый модуль, а не как скрипт:

        1. В консоли смените директорию на test/ .
        2. Запустите python -m packA.a2 .

        2. Использовать абсолютные импорты относительно директории test/ (средняя колонка в таблице). Это гарантирует, что запуск start.py напрямую всегда сработает. Чтобы запустить a2.py напрямую, можно изменить sys.path в a2.py , чтобы включить test/packA/ перед импортом sa2 .

        Примечание Обычно этот метод работает, однако в некоторых случаях переменная __file__ может быть неправильной. В таком случае нужно использовать встроенный пакет inspect . Подробнее в этом ответе на StackOverflow.

        3. Использовать только Python 2 и неявные относительные импорты (последняя колонка в таблице).

        4. Использовать абсолютные импорты относительно директории test/ и добавить её в переменную среды PYTHONPATH . Это решение не переносимо, поэтому лучше не использовать его. О том, как добавить директорию в PYTHONPATH , читайте в этом ответе.

        Пример 3: sys.path мог измениться (вариант 2)

        А вот ещё одна проблема посложнее. Допустим, модуль a2.py никогда не надо запускать напрямую, но он импортируется start.py и a1.py , которые запускаются напрямую.

        В этом случае первое решение из примера выше не сработает. Тем не менее, всё ещё можно использовать остальные решения.

        Пример 4: импорт из родительской директории

        Если мы не изменяем PYTHONPATH и стараемся не изменять sys.path программно, то сталкиваемся со следующим основным ограничением импортов в Python: при запуске скрипта напрямую невозможно импортировать что-либо из его родительской директории.

        Например, если бы нам пришлось запустить python sa1.py , то этот модуль не смог бы ничего импортировать из a1.py без вмешательства в PYTHONPATH или sys.path .

        На первый взгляд может показаться, что относительные импорты (например from .. import a1 ) помогут решить эту проблему. Однако запускаемый скрипт (в данном случае sa1.py ) считается «модулем верхнего уровня». Попытка импортировать что-либо из директории над этим скриптом приведёт к ошибке ValueError: attempted relative import beyond top-level package .

        Для решения этой проблемы лучше её не создавать и избегать написания скриптов, которые импортируют из родительской директории. Если этого нельзя избежать, то предпочтительным обходным путём является изменение sys.path .

        Python 2 vs Python 3

        Мы разобрали основные отличия импортов в Python 2 и Python 3. Они ещё раз изложены здесь наряду с менее важными отличиями:

        What is __init__.py for?

        What is __init__.py for in a Python source directory?

        Mateen Ulhaq's user avatar

        14 Answers 14

        Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The __init__.py file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.

        But just click the link, it contains an example, more information, and an explanation of namespace packages, the kind of packages without __init__.py .

        Files named __init__.py are used to mark directories on disk as Python package directories. If you have the files

        and mydir is on your path, you can import the code in module.py as

        If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

        The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc. Given the example above, the contents of the init module can be accessed as

        In addition to labeling a directory as a Python package and defining __all__ , __init__.py allows you to define any variable at the package level. Doing so is often convenient if a package defines something that will be imported frequently, in an API-like fashion. This pattern promotes adherence to the Pythonic «flat is better than nested» philosophy.

        An example

        Here is an example from one of my projects, in which I frequently import a sessionmaker called Session to interact with my database. I wrote a «database» package with a few modules:

        My __init__.py contains the following code:

        Since I define Session here, I can start a new session using the syntax below. This code would be the same executed from inside or outside of the «database» package directory.

        Of course, this is a small convenience — the alternative would be to define Session in a new file like «create_session.py» in my database package, and start new sessions using:

        Further reading

        There is a pretty interesting reddit thread covering appropriate uses of __init__.py here:

        The majority opinion seems to be that __init__.py files should be very thin to avoid violating the «explicit is better than implicit» philosophy.

        Nathan Gould's user avatar

        There are 2 main reasons for __init__.py

        For convenience: the other users will not need to know your functions’ exact location in your package hierarchy (documentation).

        then others can call add() by

        without knowing file1’s inside functions, like

        If you want something to be initialized; for example, logging (which should be put in the top level):

        The __init__.py file makes Python treat directories containing it as modules.

        Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.

        Since Python 3.3, __init__.py is no longer required to define directories as importable Python packages.

        Native support for package directories that don’t require __init__.py marker files and can automatically span multiple path segments (inspired by various third party approaches to namespace packages, as described in PEP 420)

        Although Python works without an __init__.py file you should still include one.

        It specifies that the directory should be treated as a package, so therefore include it (even if it is empty).

        There is also a case where you may actually use an __init__.py file:

        Imagine you had the following file structure:

        And methods.py contained this:

        To use foo() you would need one of the following:

        Maybe there you need (or want) to keep methods.py inside main_methods (runtimes/dependencies for example) but you only want to import main_methods .

        If you changed the name of methods.py to __init__.py then you could use foo() by just importing main_methods :

        This works because __init__.py is treated as part of the package.

        Some Python packages actually do this. An example is with JSON, where running import json is actually importing __init__.py from the json package (see the package file structure here):

        Source code: Lib/json/__init__.py

        sanjarcode's user avatar

        Xantium's user avatar

        In Python the definition of package is very simple. Like Java the hierarchical structure and the directory structure are the same. But you have to have __init__.py in a package. I will explain the __init__.py file with the example below:

        __init__.py can be empty, as long as it exists. It indicates that the directory should be regarded as a package. Of course, __init__.py can also set the appropriate content.

        If we add a function in module_n1:

        Then we followed the hierarchy package and called module_n1 the function. We can use __init__.py in subPackage_b like this:

        Hence using * importing, module package is subject to __init__.py content.

        __init__.py will treat the directory it is in as a loadable module.

        For people who prefer reading code, I put Two-Bit Alchemist’s comment here.

        B.Mr.W.'s user avatar

        It facilitates importing other python files. When you placed this file in a directory (say stuff)containing other py files, then you can do something like import stuff.other.

        Without this __init__.py inside the directory stuff, you couldn’t import other.py, because Python doesn’t know where the source code for stuff is and unable to recognize it as a package.

        An __init__.py file makes imports easy. When an __init__.py is present within a package, function a() can be imported from file b.py like so:

        Without it, however, you can’t import directly. You have to amend the system path:

        Alec's user avatar

        One thing __init__.py allows is converting a module to a package without breaking the API or creating extraneous nested namespaces or private modules*. This helps when I want to extend a namespace.

        If I have a file util.py containing

        then users will access foo with

        If I then want to add utility functions for database interaction, and I want them to have their own namespace under util , I’ll need a new directory**, and to keep API compatibility (so that from util import foo still works), I’ll call it util/. I could move util.py into util/ like so,

        and in util/__init__.py do

        but this is redundant. Instead of having a util/util.py file, we can just put the util.py contents in __init__.py and the user can now

        I think this nicely highlights how a util package’s __init__.py acts in a similar way to a util module

        * this is hinted at in the other answers, but I want to highlight it here
        ** short of employing import gymnastics. Note it won’t work to create a new package with the same name as the file, see this

        joel's user avatar

        If you’re using Python 2 and want to load siblings of your file you can simply add the parent folder of your file to your system paths of the session. It will behave about the same as if your current file was an init file.

        After that regular imports relative to the file’s directory will work just fine. E.g.

        Generally you want to use a proper init.py file instead though, but when dealing with legacy code you might be stuck with f.ex. a library hard-coded to load a particular file and nothing but. For those cases this is an alternative.

        __init__.py : It is a Python file found 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, i.e. whenever the package is imported the python statements are executed first before the other modules in this folder gets executed. It is similar to main function of c or Java program, but this exists in the Python package module (folder) rather than in the core Python file. also it has access to global variables defined in this __init__.py file as when the module is imported into Python file.

        for eg.
        I have a __init__.py file in a folder called pymodlib , this file contains the following statements:

        When I import this package pymodlib in my solution module or notebook or python console:
        These two statements get executed while importing. So in the log or console you would see the following output:

        in the next statement of python console: I can access the global variable:

        it gives the following output:

        Now, from Python 3.3 onwards the use of this file has been optional to make folder a Python module. So you can skip from including it in the python module folder.

        Покоряем Python — уроки для начинающих

        Если вы решили использовать импортирование пакетов, существует еще одно условие, которое необходимо будет соблюдать: каждый каталог в пути, указанном в инструкции импортирования пакета, должен содержать файл с именем __init__.py, в противном случае операция импорта пакета будет терпеть неудачу. То есть в примере выше каталоги dir1 и dir2 должны содержать файл с именем __init__.py каталог-контейнер dir0 может не содержать такой файл, потому что сам он не указан в инструкции импортирования пакета. Точнее говоря, для такой структуры каталогов:
        dir0\dir1\dir2\mod.py
        и инструкции импортирования, имеющей следующий вид:
        import dir1.dir2.mod
        применяются следующие правила:
        • dir1 и dir2 должны содержать файл __init__.py .
        • dir0 , каталог-контейнер, может не содержать файл __init__.py – этот файл
        будет проигнорирован, если он присутствует.
        • dir0 , но не dir0\dir1 , должен присутствовать в пути поиска модулей (то есть он должен быть домашним каталогом или присутствовать в переменной окружения PYTHONPATH и так далее).

        Таким образом, структура каталогов в этом примере должна иметь следующий вид (здесь отступы указывают на вложенность каталогов):

        dir0\ # Каталог-контейнер в пути поиска модулей
        dir1\
        __init__.py
        dir2\
        __init__.py
        mod.py
        Файлы __init__.py могут содержать программный код на языке Python, как любые другие файлы модулей. Отчасти они являются объявлениями для интерпретатора и могут вообще ничего не содержать. Эти файлы, будучи объявлениями, предотвращают неумышленное сокрытие в каталогах с совпадающими именами истинно требуемых модулей, если они отображаются позже в списке путей поиска модулей. Без этого защитного механизма интерпретатор мог бы выбирать каталоги, которые не имеют никакого отношения к вашему программному коду, только лишь потому, что в пути поиска они появляются ранее.
        В общем случае файл __init__.py предназначен для выполнения действий по инициализации пакета, создания пространства имен для каталога и реализации поведения инструкций from * (то есть from . import *), когда они используются для импортирования каталогов:

        Инициализация пакета
        Когда интерпретатор Python импортрирует каталог в первый раз он автоматически запускает программный код файла __init__.py этого каталога. По этой причине обычно в эти файлы помещается программный код, выполняющий действия по инициализации, необходимые для файлов в пакете.
        Например, этот файл инициализации в пакете может использоваться для создания файлов с данными, открытия соединения с базой данных и так далее. Обычно файлы __init__.py не предназначены для непосредственного выполнения – они запускаются автоматически, когда выполняется первое обращение к пакету.

        Инициализация пространства имен модуля
        При импортировании пакетов пути к каталогам в вашем сценарии после завершения операции импортирования превращаются в настоящие иерархии вложенных объектов. Например, в предыдущем примере после завершения операции импортирования можно будет использовать выражение dir1.dir2 , которое возвращает объект модуля, чье пространство имен содержит все имена, определяемые файлом __init__.py из каталога dir2 . Такие файлы создают пространства имен для объектов модулей, соответствующих каталогам, в которых отсутствуют настоящие файлы модулей.

        Поведение инструкции  from *
        В качестве дополнительной особенности, в файлах __init__.py можно использовать списки __all__ , чтобы определить, что будет импортироваться из каталога инструкцией from *. Список __all__ в файлах __init__.py представляет собой список имен субмодулей, которые должны импортироваться, когда в инструкции from * указывается имя пакета (каталога). Если список __all__ отсутствует, инструкция from * не будет автоматически загружать субмодули, вложенные в каталог, – она загрузит только имена,
        определяемые инструкциями присваивания в файле __init__.py , включая любые субмодули, явно импортируемые программным кодом в этом файле. Например, инструкция from submodule import X в файле __init__.py создаст имя X в пространстве имен каталога. (Мы поближе познакомимся со списком __all__ в следующих постах.)
        Эти файлы можно оставить пустыми, если вам не требуется выполнять специальных действий. Однако для успешного выполнения операции импортирования каталогов они должны существовать обязательно.

        Эти файлы можно оставить пустыми, если вам не требуется выполнять специальных действий. Однако для успешного выполнения операции импортирования каталогов они должны существовать обязательно.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *