SlideShare a Scribd company logo
Summarize Python Import
For beginner
Yuki Nishiwaki
Agenda
1.Module Overview
2.How to import
3.Module have some feature like single-tone
4.Module search path
1. The site.py
2. Usecase of pth file
What's module
● The entity to aggregate following entities
– Functions
– Classes
– modules(nested)
● Multiple modules are aggregated by Package
– But There is no entity in the run-time of Python
– recognized as module to have special behavior
– The module to be recognized as package should
have __path__ attribute
How is defined
Test/ ← package
├── __init__.py ← package need this file
├── non_package ← not package and module
├── test2
│ ├── __init__.py
│ └── test_module.py
└── test_module.py ← module
The directory that have __init__.py is recognized as Package.
The Module is defined as file and module name should be equal
to file name.
How to import module
import module_name
module.methodA() #-> something happen
You can call function in module_name with
module_name.methodA
You can call function in module_name with methodA
from module_name as methodA
ModuleA() #-> something happen
Implicit relative import
├── not_call.py
└── test
├── __init__.py
├── not_call.py
└── test_module.py
test/__init__.py
import not_call
$python3
>>> import test
$python2
>>> import test
Python2
Python3
As long as you can see, The path is not
included to express for relatives.
But we could import the packages based on
relatives path in python2. The reason why is
python2 search directory same as source to
execute import at first with implication.
From python3, we can't import relative
package with implication. But we can import
that with explication.
from . import not_call
The import sentence did roughly
1. Module Load
a. Try to search the module in cache
b. Read program and create module object
c. Cache it in sys.modules dictionaries
2. Bind namespace to current scope
a. Bind so name is associated with module
b. You can't use module until bind is done
The from-import did roughly
1. Module Load
a. Omit explanation due to same flow as import
2. Insert module to local variables
a. Prepare the variable
b. Insert the target (from hoge import hoge_func)
c. The target will be separated from module object
In other words
from mod import name1, name2
import mod
name1 = mod.name1
name2 = mod.name2
del mod
↑ is equals to ↓
Module is like single-tone object
● Once module is loaded, that is cached in
sys.modules dictionaries.
sys.modules = {
'module.name' : module object
}
● Since second time to try to import, Python
return the module from this dictionaries.
● We don't need to care for includ guard like C
– This cache search is done before read program file
is read file thus this mechanism contribute
performance up.
Break the behavior of single tone
● If delete the cache from sys.modules, single
tone behavior will be able to break
sys.modules
module_z
'module_z' → 4513070224 ・ ・
memory
4513070224
import module_z
test1.py test2.py
import module_z
break.py
import sys
del sys.modules['module_z']
import module_z
module_z
4513089454
4513089454
modue_z is test2.mozule_z
#=> False
modue_z is test2.mozule_z
#=> False
modue_z is test1.mozule_z
#=> True
How can I update cached module
● Delete cache and re-import with import sentence
– As I mentioned, This break single tone behavior
● Use reload() function
– This perform reload and store where same address.
>>> import datetime
>>> id(datetime)
4444653560
>>> reload(datetime)
<module 'datetime' from '/System/Library/lib/python2.7/lib-dynload/datetime.so'>
>>> id(datetime)
4444653560
>>> import datetime
>>> id(datetime)
4434683840
>>> del sys.modules['datetime']; import datetime
>>> id(datetime)
4434684232
Package have special behavior
>>> import test
<module 'test' from 'test/__init__.pyc'>
>>> dir(test)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> locals().keys()
['test', '__warningregistry__', '__builtins__', '__package__', '__name__', '__doc__']
>>> import test.test_module
<module 'test.test_module' from 'test/test_module.py'>
>>> dir(test)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'test_module']
>>> locals().keys()
['test', '__warningregistry__', '__builtins__', '__package__', 'sys', '__name__', '__doc__']
└── test
├── __init__.py
└── test_module.py
Added module under package
to module of package
Module search path
Search Order:
● Search in ascending order of sys.path array
How to customize the module search path:
1. Add it to PYTHONPATH environment variable
2. Directory mess around with sys.path array
3. Create hoge.pth file under site-packages dir
- Add path to hoge.pth
- Write one-line code to add module to sys.modules
site.py
● This is evaluated when initialized python run-time
– If -S options is passed, site.py call will be skipped.
● This program did followings
– Add site-packages path to sys.path
– Format the relatives path to absolute path in sys.path
– Evaluate *.pth under site-packages
● If start with import, this file is recognized as Python one-line
program and exec this code.
● If not start with import, this file is recognized as the groups to
describe multiple path and add these to sys.path
– hoge.pth will be only treated by this program
● *.pth files all need to be located under site-packages dir
Environment vars associated
● $PYTHONPATH isn't handled by this program
– Before site.py is executed it's already cared for
sys.pth
● Mainly environment vars are used to assume
– What is the path of site-package
– which site-package dir is used.
Used following environment vars
$HOME :
Only mac. Use to assume site-packages path under user
home directory. In the case of Mac sometimes Python is
installed under $HOME/Library.
$PYTHONUSERBASE:
We can add user specific site-package path like
(~/.local/lib/python2.7/site-packages). The head of these
to .local dir can be specified like
(/ukinau/lib/python2.7/site-packages)
The sample of *.pth file
----ndg_httpsclients(1/2)----
How to install this sample:
● You can install this by “pip install ndg_httpsclients”
Why do we need the pth file for this package:
● The top directory(ndg) doesn't have __init__.py
● In the case of earlier version than Python3.3, we can't
load the module which doesn't have __init__.py (PEP420
Implicit Namespace package)
● Add module directly to sys.modules with one-liner code of
pth file so that we could import in the case of earlier than
it as well.
The sample of *.pth file
----ndg_httpsclients(2/2)----
1: import sys, types, os;
2: p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('ndg',));
#=> Access attr in source of call
#=> p = lib/python2.7/site-packages/ndg
3: ie = os.path.exists(os.path.join(p,'__init__.py'));
#=> ie = False (because ndg directory doesn't have __init__.py, so we add module by
this pth file)
4: m = not ie and sys.modules.setdefault('ndg',types.ModuleType('ndg'));
#=> True and sys.modules.setdefault('ndg', <module ndg>)
#=> m = <module ndg>
5: mp = (m or []) and m.__dict__.setdefault('__path__',[]);
#=> mp = m.__path__
6: (p not in mp) and mp.append(p)
#=> m.__path__.append('lib/python2.7/site-packages/ndg') <= Finish to create package
The rest of interest for import
● Inner mechanism like how to treat __path__
● Hook mechanism (PEP302)
● Imp built-in module
– Interface to be used by implementation of import
A little get off the import
● Plugin mechanism / Dynamically module load
To be continued to later.....
Ad

More Related Content

What's hot (20)

Page cache in Linux kernel
Page cache in Linux kernelPage cache in Linux kernel
Page cache in Linux kernel
Adrian Huang
 
Linux Kernel - Virtual File System
Linux Kernel - Virtual File SystemLinux Kernel - Virtual File System
Linux Kernel - Virtual File System
Adrian Huang
 
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedVmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Adrian Huang
 
Multi threading
Multi threadingMulti threading
Multi threading
PavanAnudeepMotiki
 
Decompressed vmlinux: linux kernel initialization from page table configurati...
Decompressed vmlinux: linux kernel initialization from page table configurati...Decompressed vmlinux: linux kernel initialization from page table configurati...
Decompressed vmlinux: linux kernel initialization from page table configurati...
Adrian Huang
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
Sonam Sharma
 
2015 bioinformatics bio_python
2015 bioinformatics bio_python2015 bioinformatics bio_python
2015 bioinformatics bio_python
Prof. Wim Van Criekinge
 
Threads
ThreadsThreads
Threads
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH, SINDH, PAKISTAN
 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide Line
Gagan Vishal Mishra
 
CORE JAVA-2
CORE JAVA-2CORE JAVA-2
CORE JAVA-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Multithreading by rj
Multithreading by rjMultithreading by rj
Multithreading by rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
srgoc
srgocsrgoc
srgoc
Gaurav Singh
 
Tech talk
Tech talkTech talk
Tech talk
Preeti Patwa
 
Node.js and websockets intro
Node.js and websockets introNode.js and websockets intro
Node.js and websockets intro
kompozer
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
Ghadeer AlHasan
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Boostライブラリ一周の旅
Boostライブラリ一周の旅 Boostライブラリ一周の旅
Boostライブラリ一周の旅
Akira Takahashi
 
[Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join
[Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join[Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join
[Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join
Loiane Groner
 
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
Mohammad Reza Kamalifard
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Page cache in Linux kernel
Page cache in Linux kernelPage cache in Linux kernel
Page cache in Linux kernel
Adrian Huang
 
Linux Kernel - Virtual File System
Linux Kernel - Virtual File SystemLinux Kernel - Virtual File System
Linux Kernel - Virtual File System
Adrian Huang
 
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedVmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Adrian Huang
 
Decompressed vmlinux: linux kernel initialization from page table configurati...
Decompressed vmlinux: linux kernel initialization from page table configurati...Decompressed vmlinux: linux kernel initialization from page table configurati...
Decompressed vmlinux: linux kernel initialization from page table configurati...
Adrian Huang
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
Sonam Sharma
 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide Line
Gagan Vishal Mishra
 
Node.js and websockets intro
Node.js and websockets introNode.js and websockets intro
Node.js and websockets intro
kompozer
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
Ghadeer AlHasan
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Boostライブラリ一周の旅
Boostライブラリ一周の旅 Boostライブラリ一周の旅
Boostライブラリ一周の旅
Akira Takahashi
 
[Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join
[Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join[Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join
[Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join
Loiane Groner
 
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
Mohammad Reza Kamalifard
 

Similar to Python import mechanism (20)

Pythonpresent
PythonpresentPythonpresent
Pythonpresent
Chui-Wen Chiu
 
CLTL python course: Object Oriented Programming (2/3)
CLTL python course: Object Oriented Programming (2/3)CLTL python course: Object Oriented Programming (2/3)
CLTL python course: Object Oriented Programming (2/3)
Rubén Izquierdo Beviá
 
packages.pptx
packages.pptxpackages.pptx
packages.pptx
SHAIKIRFAN715544
 
Modules and Packages in Python_Basics.pdf
Modules and Packages in Python_Basics.pdfModules and Packages in Python_Basics.pdf
Modules and Packages in Python_Basics.pdf
RavindraTambe3
 
Modules 101
Modules 101Modules 101
Modules 101
gjcross
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Using Python Libraries.pdf
Using Python Libraries.pdfUsing Python Libraries.pdf
Using Python Libraries.pdf
SoumyadityaDey
 
library-basics python.pptx for education
library-basics python.pptx for educationlibrary-basics python.pptx for education
library-basics python.pptx for education
ShubhamShinde648276
 
Effective Python Package Management [PyCon Canada 2017]
Effective Python Package Management [PyCon Canada 2017]Effective Python Package Management [PyCon Canada 2017]
Effective Python Package Management [PyCon Canada 2017]
Devon Bernard
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Object oriented programming design and implementation
Object oriented programming design and implementationObject oriented programming design and implementation
Object oriented programming design and implementation
afsheenfaiq2
 
Object oriented programming design and implementation
Object oriented programming design and implementationObject oriented programming design and implementation
Object oriented programming design and implementation
afsheenfaiq2
 
Python module 3, b.tech 5th semester ppt
Python module 3, b.tech 5th semester pptPython module 3, b.tech 5th semester ppt
Python module 3, b.tech 5th semester ppt
course5325
 
How to Build a Module in Odoo 15 Scaffold Method
How to Build a Module in Odoo 15 Scaffold MethodHow to Build a Module in Odoo 15 Scaffold Method
How to Build a Module in Odoo 15 Scaffold Method
Celine George
 
python_models_import_main_init_presentation.ppt
python_models_import_main_init_presentation.pptpython_models_import_main_init_presentation.ppt
python_models_import_main_init_presentation.ppt
gouthamsaisurya555
 
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp dmod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
paurushsinhad
 
jb_Modules_in_Python.ppt
jb_Modules_in_Python.pptjb_Modules_in_Python.ppt
jb_Modules_in_Python.ppt
loliktry
 
Class 12 CBSE Chapter: python libraries.pptx
Class 12 CBSE Chapter: python libraries.pptxClass 12 CBSE Chapter: python libraries.pptx
Class 12 CBSE Chapter: python libraries.pptx
AravindVaithianadhan
 
package module in the python environement.pptx
package module in the python environement.pptxpackage module in the python environement.pptx
package module in the python environement.pptx
MuhammadAbdullah311866
 
Python Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptxPython Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptx
Singamvineela
 
CLTL python course: Object Oriented Programming (2/3)
CLTL python course: Object Oriented Programming (2/3)CLTL python course: Object Oriented Programming (2/3)
CLTL python course: Object Oriented Programming (2/3)
Rubén Izquierdo Beviá
 
Modules and Packages in Python_Basics.pdf
Modules and Packages in Python_Basics.pdfModules and Packages in Python_Basics.pdf
Modules and Packages in Python_Basics.pdf
RavindraTambe3
 
Modules 101
Modules 101Modules 101
Modules 101
gjcross
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Using Python Libraries.pdf
Using Python Libraries.pdfUsing Python Libraries.pdf
Using Python Libraries.pdf
SoumyadityaDey
 
library-basics python.pptx for education
library-basics python.pptx for educationlibrary-basics python.pptx for education
library-basics python.pptx for education
ShubhamShinde648276
 
Effective Python Package Management [PyCon Canada 2017]
Effective Python Package Management [PyCon Canada 2017]Effective Python Package Management [PyCon Canada 2017]
Effective Python Package Management [PyCon Canada 2017]
Devon Bernard
 
Object oriented programming design and implementation
Object oriented programming design and implementationObject oriented programming design and implementation
Object oriented programming design and implementation
afsheenfaiq2
 
Object oriented programming design and implementation
Object oriented programming design and implementationObject oriented programming design and implementation
Object oriented programming design and implementation
afsheenfaiq2
 
Python module 3, b.tech 5th semester ppt
Python module 3, b.tech 5th semester pptPython module 3, b.tech 5th semester ppt
Python module 3, b.tech 5th semester ppt
course5325
 
How to Build a Module in Odoo 15 Scaffold Method
How to Build a Module in Odoo 15 Scaffold MethodHow to Build a Module in Odoo 15 Scaffold Method
How to Build a Module in Odoo 15 Scaffold Method
Celine George
 
python_models_import_main_init_presentation.ppt
python_models_import_main_init_presentation.pptpython_models_import_main_init_presentation.ppt
python_models_import_main_init_presentation.ppt
gouthamsaisurya555
 
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp dmod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
paurushsinhad
 
jb_Modules_in_Python.ppt
jb_Modules_in_Python.pptjb_Modules_in_Python.ppt
jb_Modules_in_Python.ppt
loliktry
 
Class 12 CBSE Chapter: python libraries.pptx
Class 12 CBSE Chapter: python libraries.pptxClass 12 CBSE Chapter: python libraries.pptx
Class 12 CBSE Chapter: python libraries.pptx
AravindVaithianadhan
 
package module in the python environement.pptx
package module in the python environement.pptxpackage module in the python environement.pptx
package module in the python environement.pptx
MuhammadAbdullah311866
 
Python Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptxPython Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptx
Singamvineela
 
Ad

Recently uploaded (20)

Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
Meet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Meet the New Kid in the Sandbox - Integrating Visualization with PrometheusMeet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Meet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Eric D. Schabell
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by AjathMobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Ajath Infotech Technologies LLC
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
The Elixir Developer - All Things Open
The Elixir Developer - All Things OpenThe Elixir Developer - All Things Open
The Elixir Developer - All Things Open
Carlo Gilmar Padilla Santana
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
Meet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Meet the New Kid in the Sandbox - Integrating Visualization with PrometheusMeet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Meet the New Kid in the Sandbox - Integrating Visualization with Prometheus
Eric D. Schabell
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by AjathMobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Ajath Infotech Technologies LLC
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Ad

Python import mechanism

  • 1. Summarize Python Import For beginner Yuki Nishiwaki
  • 2. Agenda 1.Module Overview 2.How to import 3.Module have some feature like single-tone 4.Module search path 1. The site.py 2. Usecase of pth file
  • 3. What's module ● The entity to aggregate following entities – Functions – Classes – modules(nested) ● Multiple modules are aggregated by Package – But There is no entity in the run-time of Python – recognized as module to have special behavior – The module to be recognized as package should have __path__ attribute
  • 4. How is defined Test/ ← package ├── __init__.py ← package need this file ├── non_package ← not package and module ├── test2 │ ├── __init__.py │ └── test_module.py └── test_module.py ← module The directory that have __init__.py is recognized as Package. The Module is defined as file and module name should be equal to file name.
  • 5. How to import module import module_name module.methodA() #-> something happen You can call function in module_name with module_name.methodA You can call function in module_name with methodA from module_name as methodA ModuleA() #-> something happen
  • 6. Implicit relative import ├── not_call.py └── test ├── __init__.py ├── not_call.py └── test_module.py test/__init__.py import not_call $python3 >>> import test $python2 >>> import test Python2 Python3 As long as you can see, The path is not included to express for relatives. But we could import the packages based on relatives path in python2. The reason why is python2 search directory same as source to execute import at first with implication. From python3, we can't import relative package with implication. But we can import that with explication. from . import not_call
  • 7. The import sentence did roughly 1. Module Load a. Try to search the module in cache b. Read program and create module object c. Cache it in sys.modules dictionaries 2. Bind namespace to current scope a. Bind so name is associated with module b. You can't use module until bind is done
  • 8. The from-import did roughly 1. Module Load a. Omit explanation due to same flow as import 2. Insert module to local variables a. Prepare the variable b. Insert the target (from hoge import hoge_func) c. The target will be separated from module object
  • 9. In other words from mod import name1, name2 import mod name1 = mod.name1 name2 = mod.name2 del mod ↑ is equals to ↓
  • 10. Module is like single-tone object ● Once module is loaded, that is cached in sys.modules dictionaries. sys.modules = { 'module.name' : module object } ● Since second time to try to import, Python return the module from this dictionaries. ● We don't need to care for includ guard like C – This cache search is done before read program file is read file thus this mechanism contribute performance up.
  • 11. Break the behavior of single tone ● If delete the cache from sys.modules, single tone behavior will be able to break sys.modules module_z 'module_z' → 4513070224 ・ ・ memory 4513070224 import module_z test1.py test2.py import module_z break.py import sys del sys.modules['module_z'] import module_z module_z 4513089454 4513089454 modue_z is test2.mozule_z #=> False modue_z is test2.mozule_z #=> False modue_z is test1.mozule_z #=> True
  • 12. How can I update cached module ● Delete cache and re-import with import sentence – As I mentioned, This break single tone behavior ● Use reload() function – This perform reload and store where same address. >>> import datetime >>> id(datetime) 4444653560 >>> reload(datetime) <module 'datetime' from '/System/Library/lib/python2.7/lib-dynload/datetime.so'> >>> id(datetime) 4444653560 >>> import datetime >>> id(datetime) 4434683840 >>> del sys.modules['datetime']; import datetime >>> id(datetime) 4434684232
  • 13. Package have special behavior >>> import test <module 'test' from 'test/__init__.pyc'> >>> dir(test) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__'] >>> locals().keys() ['test', '__warningregistry__', '__builtins__', '__package__', '__name__', '__doc__'] >>> import test.test_module <module 'test.test_module' from 'test/test_module.py'> >>> dir(test) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'test_module'] >>> locals().keys() ['test', '__warningregistry__', '__builtins__', '__package__', 'sys', '__name__', '__doc__'] └── test ├── __init__.py └── test_module.py Added module under package to module of package
  • 14. Module search path Search Order: ● Search in ascending order of sys.path array How to customize the module search path: 1. Add it to PYTHONPATH environment variable 2. Directory mess around with sys.path array 3. Create hoge.pth file under site-packages dir - Add path to hoge.pth - Write one-line code to add module to sys.modules
  • 15. site.py ● This is evaluated when initialized python run-time – If -S options is passed, site.py call will be skipped. ● This program did followings – Add site-packages path to sys.path – Format the relatives path to absolute path in sys.path – Evaluate *.pth under site-packages ● If start with import, this file is recognized as Python one-line program and exec this code. ● If not start with import, this file is recognized as the groups to describe multiple path and add these to sys.path – hoge.pth will be only treated by this program ● *.pth files all need to be located under site-packages dir
  • 16. Environment vars associated ● $PYTHONPATH isn't handled by this program – Before site.py is executed it's already cared for sys.pth ● Mainly environment vars are used to assume – What is the path of site-package – which site-package dir is used.
  • 17. Used following environment vars $HOME : Only mac. Use to assume site-packages path under user home directory. In the case of Mac sometimes Python is installed under $HOME/Library. $PYTHONUSERBASE: We can add user specific site-package path like (~/.local/lib/python2.7/site-packages). The head of these to .local dir can be specified like (/ukinau/lib/python2.7/site-packages)
  • 18. The sample of *.pth file ----ndg_httpsclients(1/2)---- How to install this sample: ● You can install this by “pip install ndg_httpsclients” Why do we need the pth file for this package: ● The top directory(ndg) doesn't have __init__.py ● In the case of earlier version than Python3.3, we can't load the module which doesn't have __init__.py (PEP420 Implicit Namespace package) ● Add module directly to sys.modules with one-liner code of pth file so that we could import in the case of earlier than it as well.
  • 19. The sample of *.pth file ----ndg_httpsclients(2/2)---- 1: import sys, types, os; 2: p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('ndg',)); #=> Access attr in source of call #=> p = lib/python2.7/site-packages/ndg 3: ie = os.path.exists(os.path.join(p,'__init__.py')); #=> ie = False (because ndg directory doesn't have __init__.py, so we add module by this pth file) 4: m = not ie and sys.modules.setdefault('ndg',types.ModuleType('ndg')); #=> True and sys.modules.setdefault('ndg', <module ndg>) #=> m = <module ndg> 5: mp = (m or []) and m.__dict__.setdefault('__path__',[]); #=> mp = m.__path__ 6: (p not in mp) and mp.append(p) #=> m.__path__.append('lib/python2.7/site-packages/ndg') <= Finish to create package
  • 20. The rest of interest for import ● Inner mechanism like how to treat __path__ ● Hook mechanism (PEP302) ● Imp built-in module – Interface to be used by implementation of import A little get off the import ● Plugin mechanism / Dynamically module load To be continued to later.....
  翻译: