Система модулей даёт возможность логически организовать код на Python. Кроме того, группирование в модули значительно облегчает сам процесс написания кода, плюс делает его более понятным. В этой статье поговорим, что такое модуль в Python, где он хранится и как обрабатывается.
Модуль в Python — это файл, в котором содержится код на Python. Любой модуль в Python может включать в себя переменные, объявления функций и классов. Вдобавок ко всемe, в модуле может содержаться исполняемый код.
Команда import в Python
Позволяет использовать любой файл Python в качестве модуля в другом файле. Синтаксис прост:
import module_1[, module_2[,... module_N]Как только Python-интерпретатор встречает команду import, он выполняет импорт модуля, если он есть в пути поиска Python. Что касается пути поиска Python, то речь идёт о списке директорий, в которых интерпретатор выполняет поиск перед загрузкой модуля. Посмотрите на пример кода при использовании модуля math:
import math # Используем функцию sqrt из модуля math print (math.sqrt(9)) # Печатаем значение переменной pi, определенной в math print (math.pi)Помните, что модуль загружается только один раз, вне зависимости от того, какое количество раз вы его импортировали. Таким образом исключается цикличное выполнение содержимого модуля.
Команда from … import
Команда from … import даёт возможность выполнить импорт не всего модуля целиком, а лишь конкретного его содержимого:
# Импортируем из модуля math функцию sqrt from math import sqrt # Выводим результат выполнения функции sqrt. # Нам больше незачем указывать имя модуля print (sqrt(144)) # Но мы уже не можем получить из модуля то, что не импортировали print (pi) # Выдаст ошибкуОбратите внимание, что выражение from … import не импортирует модуль полностью, а лишь предоставляет доступ к объектам, указанным нами.
Команда from … import *
Также в Python мы можем импортировать из модуля переменные, классы и функции за один раз. Чтобы это выполнить, применяется конструкция from … import *:
from math import * # Теперь у нас есть доступ ко всем функция и переменным, определенным в модуле math print (sqrt(121)) print (pi) print (e)
Использовать данную конструкцию нужно осторожно, ведь при импорте нескольких модулей можно запутаться в собственном коде.
![]()
Так где хранятся модули в Python?
При импорте модуля, интерпретатор Python пытается найти модуль в следующих местах:
1. Директория, где находится файл, в котором вызывается команда импорта.
2. Директория, определённая в консольной переменной PYTHONPATH (если модуль не найден с первого раза).
3. Путь, заданный по умолчанию (если модуль не найден в предыдущих двух случаях).Что касается пути поиска, то он сохраняется в переменной path в системном модуле sys. А переменная sys.path включает в себя все 3 вышеописанных места поиска.
![]()
Получаем список всех модулей Python
Чтобы получить полный список модулей, установленных на ПК, используют команду help(«modules»).
![]()
Создаём свой модуль в Python
Для создания собственного модуля в Python нужно сохранить ваш скрипт с расширением .py. После этого он станет доступным в любом другом файле. Давайте создадим 2 файла: module_1.py и module_2.py, а потом сохраним их в одной директории. В первом файле запишем:
def hello(): print ("Hello from module_1")А во втором вызовем функцию:
from module_1 import hello hello()После выполнения кода 2-го файла получим:
Функция dir() в Python
Возвратит отсортированный список строк с содержанием всех имён, определенных в модуле.
# на данный момент нам доступны лишь встроенные функции dir() # импортируем модуль math import math # теперь модуль math в списке доступных имен dir() # получим имена, определенные в модуле math dir(math)![]()
Пакеты модулей в Python
Несколько файлов-модулей с кодом можно объединить в пакеты модулей. Пакет модулей — это директория, включающая в себя несколько отдельных файлов-скриптов.
Представьте, что у нас следующая структура:
|_ my_file.py |_ my_package |_ __init__.py |_ inside_file.py
В файле inside_file.py определена некоторая функция foo. В итоге, дабы получить доступ к этой функции, в файле my_file нужно выполнить:
from my_package.inside_file import fooТакже нужно обратить внимание на то, есть ли внутри директории my_package файл init.py. Это может быть и пустой файл, сообщающий Python, что директория является пакетом модулей. В Python 3 включать файл init.py в пакет модулей уже не обязательно, но мы рекомендуем всё же делать это, чтобы обеспечить обратную совместимость.
![]()
To manage our resources, we should always be aware of their locations. The path of a file or a module in your local system is essential in programming. Also to optimize storage options, we should have a rough idea about file systems.
In different operating systems, the methods for a file or application search may vary. In Python, there are more than one way to find the path or the directory in which your desired module may be stored for later use or imports.
In this article, we will take a look at the various methods that you can use to search for specific files and folders in your local system.
The location type of a file or a module can be described as it’s absolute path or relative path. For example, this location:- C:\Users\SHREYA\Programs\Python311\find path.py is the absolute path of the file “find path.py”. Here the current working directory for this particular file is : C:\Users\SHREYA and it’s relative path, which is used to refer to the files related to current directory would be: Programs\Python311\find path.py .
Modules are nothing but special files which contain pre-written code for in-built functions that makes Python one of the most useful and easy-to-learn programming languages in the world. Modules are the backbone of Python which are collections of in built functions making the life of programmers all over the world easier.
Even though python modules and libraries are used interchangeably, Python libraries are a collection of python modules. You can learn more about the difference between libraries and modules
Why do We Need to Find Module Sources and File Paths?
It is essential to know the location of where our files are stored on our local machine. This helps in determining the absolute paths of modules so conflicts can be avoided and data can be read properly.
We need the sources of various files and modules due to the following reasons:-
- To manipulate data via python code, we need the PATH of a file
- To access our files easily, it’s necessary to know how to search for directories and paths
- For reading and writing in files, their locations are essential
- Python raises errors when it cannot locate specific modules
- To avoid errors such as ImportError, where conflicts can arise from duplicate file names, it’s important to know how to search for pre-existing system modules
In Python, there are three easy methods to find the location of module sources. The first is using the ‘file‘ attribute, which gives the absolute path of the current module. The second method involves the ‘help’ function, which provides comprehensive information about a module, including its location. Lastly, the ‘sys’ module can be used to list the locations where all Python modules are stored.
Method 1: The __file__ attribute
This attribute will give you the absolute path of the current file that you’re running. Let us locate the numpy module in our code by running the following code in your python terminal.
>>>import numpy #import the required module >>>print("The PATH OF THE CURRENT MODULE IS=", end=numpy.__file__)
The output would be:
The PATH OF THE CURRENT MODULE IS=C:\Users\SHREYA\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\__init__.py
Method 2: The ‘help’ function
In this method, we will import the random module in our code and determine its location using help.
>>>import random >>>print(help(random))
You’ll get a huge output with all the information about this module. And in the very end you would find it’s location mentioned.
Help on module random: NAME random - Random variable generators. MODULE REFERENCE https://docs.python.org/3.11/library/random.html The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. ............All other information FILE c:\users\shreya\appdata\local\programs\python\python311\lib\random.py
Similar : How to Check Version of Installed Python Modules.
Method 3: The ‘sys’ module
This method will list the location where all the python modules are stored. This is also one of the most common methods that is used.
>>>import sys >>>print("The location is= ", end=str(sys.path))
The output would be:
The location is= ['C:\\Users\\SHREYA\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\idlelib', 'C:\\Users\\SHREYA\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\SHREYA\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\SHREYA\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\SHREYA\\AppData\\Local\\Programs\\Python\\Python311', 'C:\\Users\\SHREYA\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages']
The output shows a list of directories where Python looks for modules. Each string in the list is a directory path where Python will search for modules when an ‘import’ statement is executed.
Demystify Python Modules and Paths
Through this guide, we’ve uncovered the mystery of Python module sources and paths. We’ve explored why they are crucial and how to identify them using three straightforward methods. Now, the power to manage your directories and local storage is in your hands. Are you ready to take your Python programming efficiency to the next level?
Last Updated :
20 Aug, 2021
Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module in that file and then we can use them. Modules can exist in various directories.
In this article, we will discuss where does python looks for modules.
Python looks for modules in 3 steps:-
- First, it searches in the current directory.
- If not found then it searches in the directories which are in shell variable PYTHONPATH
- If that also fails python checks the installation-dependent list of directories configured at the time Python is installed
Now we will discuss each of these steps:
Step 1: Firstly the python searches in the current directory. From the current directory we mean the directory in which the file calling the module exists. We can check the working directory from os module of python by os.getcwd() method. The directory returned from this method is referred to as the current directory. The code for getting the current directory is:
Python
# importing os module import os # printing the current working directory print(os.getcwd())
The output of the above code will be the current working directory which will be first searched for a module to be imported.
Step 2: If the module that needs to be imported is not found in the current directory. Then python will search it in the PYTHONPATH which is a list of directory names, with the same syntax as the shell variable PATH. To know the directories in PYTHONPATH we can simply get them by the sys module. The sys.path gives us the list of all the paths where the module will be searched when it is needed to import. To see these directories we have to write the following code:
Python
# importing the sys module import sys # printing sys.path variable of sys module print(sys.path)
Output
[‘/home’, ‘/usr/lib/python2.7’, ‘/usr/lib/python2.7/plat-x86_64-linux-gnu’, ‘/usr/lib/python2.7/lib-tk’, ‘/usr/lib/python2.7/lib-old’, ‘/usr/lib/python2.7/lib-dynload’, ‘/usr/local/lib/python2.7/dist-packages’, ‘/usr/lib/python2.7/dist-packages’]
Step 3: If the module is not found in the above 2 steps the python interpreter then tries to find it in installation dependent list of directories that are configured at the time of installation of python. These directories are also included in sys.path variable of sys module and can be known in the same way as the above step. The code will be:
Python
# importing the sys module import sys # printing sys.path variable of sys module print(sys.path)
Output
[‘/home’, ‘/usr/lib/python2.7’, ‘/usr/lib/python2.7/plat-x86_64-linux-gnu’, ‘/usr/lib/python2.7/lib-tk’, ‘/usr/lib/python2.7/lib-old’, ‘/usr/lib/python2.7/lib-dynload’, ‘/usr/local/lib/python2.7/dist-packages’, ‘/usr/lib/python2.7/dist-packages’]
Пройдите тест, узнайте какой профессии подходите
Часто при использовании инструмента для установки пакетов Python, pip, возникает вопрос о том, где именно устанавливаются загруженные пакеты. В частности,
Освойте Python на курсе от Skypro. Вас ждут 400 часов обучения и практики (достаточно десяти часов в неделю), подготовка проектов для портфолио, индивидуальная проверка домашних заданий и помощь опытных наставников. Получится, даже если у вас нет опыта в IT.
Часто при использовании инструмента для установки пакетов Python, pip, возникает вопрос о том, где именно устанавливаются загруженные пакеты. В частности, это становится актуальным, когда пользователь работает с виртуальным окружением, созданным с помощью инструмента virtualenv.
Допустим, была выполнена команда:
pip install requests
Эта команда устанавливает пакет «requests» с помощью pip. Но где именно он устанавливается? В какой директории его можно найти?
Пакеты, установленные с помощью pip, обычно устанавливаются в директории, где установлен Python. Они располагаются в поддиректории «site-packages».
Если установка происходит в виртуальном окружении, то пакеты устанавливаются в директорию этого виртуального окружения. Снова, они будут находиться в поддиректории «site-packages».
Таким образом, если, например, используется виртуальное окружение, созданное в директории «myenv», то пакеты будут установлены в директории «myenv/lib/pythonX.Y/site-packages», где «X.Y» — это версия Python, используемая в виртуальном окружении.
Если же Python и pip установлены глобально, то пакеты будут установлены в директории «lib/pythonX.Y/site-packages» в директории установки Python.
В любом случае, для того чтобы узнать точное местоположение установленного пакета, можно воспользоваться модулем «site» в Python. Следующая команда выведет список всех директорий, где pip ищет пакеты:
python -m site
Также можно использовать следующую команду для вывода директории установки конкретного пакета:
python -c "import package; print(package.__path__)"
Здесь «package» — это имя установленного пакета.
Итак, теперь стало ясно, где pip устанавливает пакеты и как найти их местоположение.
На курсе Skypro «Python-разработчик» освоите основные инструменты программирования, получите опыт на реальных проектах и сможете стартовать в профессии уверенным новичком. Преподаватели — практикующие программисты с большим опытом, а в центре карьеры помогут составить цепляющее резюме и подготовиться к собеседованию.
2023-01-31 20:21
Программирование
Время прочтения: 1 минута
Когда возникали проблемы с установками тех или иных геопространственных библиотек Python на Windows, приходилось скачивать бинарники с сайта Christoph Gohlke — Unofficial Windows Binaries for Python Extension Packages. Все форумы и гайды всегда ссылались на этот сайт, где были представлены 32- и 64-битные бинарные файлы многих пакетов с открытым исходным кодом для официального дистрибутива CPython. Несколько бинарников были доступны и для дистрибутива PyPy.
Сайт вел один человек, и сборки всех библиотек и поддержка сайта осуществлялись на базе одной из лабораторий Калифорнийского университета. 7 июня 2022 года на сайте появилась новость, что финансирование этой лаборатории заканчивается, и до конца месяца сайт перестанет работать. 26 июня вышло последнее обновление и последние сборки библиотек. После этого на сайт еще можно было зайти и скачать старые версии библиотек, но наблюдались сбои с работой сайта.
Вместо этого 5 января на гитхабе того же Christoph Gohlke появились репозитории, которые возродили этот сервис по публикации бинарников питоновских библиотек под Windows. Теперь его репозиторий GitHub предоставляет неофициальные бинарные архивы wheel для некоторых геопространственных библиотек для Python под Windows. Все можно скачать со страницы Releases.
Пользуйтесь!