ºÝºÝߣ

ºÝºÝߣShare 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
¨C Functions
¨C Classes
¨C modules(nested)
¡ñ Multiple modules are aggregated by Package
¨C But There is no entity in the run-time of Python
¨C recognized as module to have special behavior
¨C 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
¨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
¨C As I mentioned, This break single tone behavior
¡ñ Use reload() function
¨C 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
¨C If -S options is passed, site.py call will be skipped.
¡ñ This program did followings
¨C Add site-packages path to sys.path
¨C Format the relatives path to absolute path in sys.path
¨C 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
¨C 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
¨C Before site.py is executed it's already cared for
sys.pth
¡ñ Mainly environment vars are used to assume
¨C What is the path of site-package
¨C 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
¨C Interface to be used by implementation of import
A little get off the import
¡ñ Plugin mechanism / Dynamically module load
To be continued to later.....

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
?
Java NIO.2
Java NIO.2Java NIO.2
Java NIO.2
*instinctools
?
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
?
µþ´Ç´Ç²õ³Ù¥é¥¤¥Ö¥é¥êÒ»ÖܤÎÂÃ
µþ´Ç´Ç²õ³Ù¥é¥¤¥Ö¥é¥êÒ»ÖܤÎÂà µþ´Ç´Ç²õ³Ù¥é¥¤¥Ö¥é¥êÒ»ÖܤÎÂÃ
µþ´Ç´Ç²õ³Ù¥é¥¤¥Ö¥é¥êÒ»ÖܤÎÂÃ
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
?
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
?
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
?
µþ´Ç´Ç²õ³Ù¥é¥¤¥Ö¥é¥êÒ»ÖܤÎÂÃ
µþ´Ç´Ç²õ³Ù¥é¥¤¥Ö¥é¥êÒ»ÖܤÎÂà µþ´Ç´Ç²õ³Ù¥é¥¤¥Ö¥é¥êÒ»ÖܤÎÂÃ
µþ´Ç´Ç²õ³Ù¥é¥¤¥Ö¥é¥êÒ»ÖܤÎÂÃ
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 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
?
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
?
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptx
krushnaraj1
?
CLASS-11 & 12 ICT PPT Functions in Python.pptx
CLASS-11 & 12 ICT PPT Functions in Python.pptxCLASS-11 & 12 ICT PPT Functions in Python.pptx
CLASS-11 & 12 ICT PPT Functions in Python.pptx
seccoordpal
?
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 101
Modules 101Modules 101
Modules 101
gjcross
?
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
?
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
?
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptx
krushnaraj1
?
CLASS-11 & 12 ICT PPT Functions in Python.pptx
CLASS-11 & 12 ICT PPT Functions in Python.pptxCLASS-11 & 12 ICT PPT Functions in Python.pptx
CLASS-11 & 12 ICT PPT Functions in Python.pptx
seccoordpal
?

Recently uploaded (20)

Choreo - The AI-Native Internal Developer Platform as a Service: Overview
Choreo - The AI-Native Internal Developer Platform as a Service: OverviewChoreo - The AI-Native Internal Developer Platform as a Service: Overview
Choreo - The AI-Native Internal Developer Platform as a Service: Overview
WSO2
?
ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]
umeerbinfaizan
?
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlanMaximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
OnePlan Solutions
?
Clip Studio Paint EX Download (Latest 2025)
Clip Studio Paint EX Download (Latest 2025)Clip Studio Paint EX Download (Latest 2025)
Clip Studio Paint EX Download (Latest 2025)
mohsinrazakpa79
?
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odooTour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
AxisTechnolabs
?
Coreldraw 2021 Crack Latest Version 2025
Coreldraw 2021 Crack Latest Version 2025Coreldraw 2021 Crack Latest Version 2025
Coreldraw 2021 Crack Latest Version 2025
blouch31kp
?
E-commerce App Development cost in 2025.pdf
E-commerce App Development cost in 2025.pdfE-commerce App Development cost in 2025.pdf
E-commerce App Development cost in 2025.pdf
sandeepjangidimg
?
Wondershare PDFelement Pro Crack FREE Download
Wondershare PDFelement Pro Crack FREE DownloadWondershare PDFelement Pro Crack FREE Download
Wondershare PDFelement Pro Crack FREE Download
waqarcracker5
?
Movavi Screen Recorder Studio 2025 crack Free Download
Movavi Screen Recorder Studio 2025 crack Free DownloadMovavi Screen Recorder Studio 2025 crack Free Download
Movavi Screen Recorder Studio 2025 crack Free Download
imran03kr
?
Adobe Illustrator Crack Download (Latest 2025)
Adobe Illustrator Crack Download (Latest 2025)Adobe Illustrator Crack Download (Latest 2025)
Adobe Illustrator Crack Download (Latest 2025)
blouch36kp
?
ESET NOD32 Antivirus Crack with License Key 2025
ESET NOD32 Antivirus Crack with License Key 2025ESET NOD32 Antivirus Crack with License Key 2025
ESET NOD32 Antivirus Crack with License Key 2025
umeerbinfaizan
?
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with EaseCypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Shubham Joshi
?
Will Ai Eat the Industrial World? The End of Engineering as We Know it
Will Ai Eat the Industrial World? The End of Engineering as We Know itWill Ai Eat the Industrial World? The End of Engineering as We Know it
Will Ai Eat the Industrial World? The End of Engineering as We Know it
Christian Dahlen
?
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
blouch36kp
?
The Missing Voices: Unearthing the Impact of Survivorship Bias on Women in Te...
The Missing Voices: Unearthing the Impact of Survivorship Bias on Women in Te...The Missing Voices: Unearthing the Impact of Survivorship Bias on Women in Te...
The Missing Voices: Unearthing the Impact of Survivorship Bias on Women in Te...
Imma Valls Bernaus
?
Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025
mohsinrazakpa28
?
Multicompany Analytic Odoo Dashboard for POS, CRM, Inventory, Sales and Accou...
Multicompany Analytic Odoo Dashboard for POS, CRM, Inventory, Sales and Accou...Multicompany Analytic Odoo Dashboard for POS, CRM, Inventory, Sales and Accou...
Multicompany Analytic Odoo Dashboard for POS, CRM, Inventory, Sales and Accou...
AxisTechnolabs
?
IBM / MAINFRAME /RACF security-guide_pdf.pdf
IBM / MAINFRAME /RACF security-guide_pdf.pdfIBM / MAINFRAME /RACF security-guide_pdf.pdf
IBM / MAINFRAME /RACF security-guide_pdf.pdf
WILSON990330
?
Drawing Heighway¡¯s Dragon - Part II - Recursive Function Simplification - Fro...
Drawing Heighway¡¯s Dragon - Part II - Recursive Function Simplification - Fro...Drawing Heighway¡¯s Dragon - Part II - Recursive Function Simplification - Fro...
Drawing Heighway¡¯s Dragon - Part II - Recursive Function Simplification - Fro...
Philip Schwarz
?
Wondershare Filmora Crack Free Download 2025
Wondershare Filmora Crack Free Download 2025Wondershare Filmora Crack Free Download 2025
Wondershare Filmora Crack Free Download 2025
tanveerhussainkp027
?
Choreo - The AI-Native Internal Developer Platform as a Service: Overview
Choreo - The AI-Native Internal Developer Platform as a Service: OverviewChoreo - The AI-Native Internal Developer Platform as a Service: Overview
Choreo - The AI-Native Internal Developer Platform as a Service: Overview
WSO2
?
ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]
umeerbinfaizan
?
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlanMaximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
Maximizing PMI Chapter Success to Streamline Events + Programs with OnePlan
OnePlan Solutions
?
Clip Studio Paint EX Download (Latest 2025)
Clip Studio Paint EX Download (Latest 2025)Clip Studio Paint EX Download (Latest 2025)
Clip Studio Paint EX Download (Latest 2025)
mohsinrazakpa79
?
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odooTour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
AxisTechnolabs
?
Coreldraw 2021 Crack Latest Version 2025
Coreldraw 2021 Crack Latest Version 2025Coreldraw 2021 Crack Latest Version 2025
Coreldraw 2021 Crack Latest Version 2025
blouch31kp
?
E-commerce App Development cost in 2025.pdf
E-commerce App Development cost in 2025.pdfE-commerce App Development cost in 2025.pdf
E-commerce App Development cost in 2025.pdf
sandeepjangidimg
?
Wondershare PDFelement Pro Crack FREE Download
Wondershare PDFelement Pro Crack FREE DownloadWondershare PDFelement Pro Crack FREE Download
Wondershare PDFelement Pro Crack FREE Download
waqarcracker5
?
Movavi Screen Recorder Studio 2025 crack Free Download
Movavi Screen Recorder Studio 2025 crack Free DownloadMovavi Screen Recorder Studio 2025 crack Free Download
Movavi Screen Recorder Studio 2025 crack Free Download
imran03kr
?
Adobe Illustrator Crack Download (Latest 2025)
Adobe Illustrator Crack Download (Latest 2025)Adobe Illustrator Crack Download (Latest 2025)
Adobe Illustrator Crack Download (Latest 2025)
blouch36kp
?
ESET NOD32 Antivirus Crack with License Key 2025
ESET NOD32 Antivirus Crack with License Key 2025ESET NOD32 Antivirus Crack with License Key 2025
ESET NOD32 Antivirus Crack with License Key 2025
umeerbinfaizan
?
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with EaseCypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Cypress Parallel Testing Tutorial: Speed Up Your Test Runs with Ease
Shubham Joshi
?
Will Ai Eat the Industrial World? The End of Engineering as We Know it
Will Ai Eat the Industrial World? The End of Engineering as We Know itWill Ai Eat the Industrial World? The End of Engineering as We Know it
Will Ai Eat the Industrial World? The End of Engineering as We Know it
Christian Dahlen
?
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
blouch36kp
?
The Missing Voices: Unearthing the Impact of Survivorship Bias on Women in Te...
The Missing Voices: Unearthing the Impact of Survivorship Bias on Women in Te...The Missing Voices: Unearthing the Impact of Survivorship Bias on Women in Te...
The Missing Voices: Unearthing the Impact of Survivorship Bias on Women in Te...
Imma Valls Bernaus
?
Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025
mohsinrazakpa28
?
Multicompany Analytic Odoo Dashboard for POS, CRM, Inventory, Sales and Accou...
Multicompany Analytic Odoo Dashboard for POS, CRM, Inventory, Sales and Accou...Multicompany Analytic Odoo Dashboard for POS, CRM, Inventory, Sales and Accou...
Multicompany Analytic Odoo Dashboard for POS, CRM, Inventory, Sales and Accou...
AxisTechnolabs
?
IBM / MAINFRAME /RACF security-guide_pdf.pdf
IBM / MAINFRAME /RACF security-guide_pdf.pdfIBM / MAINFRAME /RACF security-guide_pdf.pdf
IBM / MAINFRAME /RACF security-guide_pdf.pdf
WILSON990330
?
Drawing Heighway¡¯s Dragon - Part II - Recursive Function Simplification - Fro...
Drawing Heighway¡¯s Dragon - Part II - Recursive Function Simplification - Fro...Drawing Heighway¡¯s Dragon - Part II - Recursive Function Simplification - Fro...
Drawing Heighway¡¯s Dragon - Part II - Recursive Function Simplification - Fro...
Philip Schwarz
?
Wondershare Filmora Crack Free Download 2025
Wondershare Filmora Crack Free Download 2025Wondershare Filmora Crack Free Download 2025
Wondershare Filmora Crack Free Download 2025
tanveerhussainkp027
?

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 ¨C Functions ¨C Classes ¨C modules(nested) ¡ñ Multiple modules are aggregated by Package ¨C But There is no entity in the run-time of Python ¨C recognized as module to have special behavior ¨C 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 ¨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 ¨C As I mentioned, This break single tone behavior ¡ñ Use reload() function ¨C 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 ¨C If -S options is passed, site.py call will be skipped. ¡ñ This program did followings ¨C Add site-packages path to sys.path ¨C Format the relatives path to absolute path in sys.path ¨C 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 ¨C 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 ¨C Before site.py is executed it's already cared for sys.pth ¡ñ Mainly environment vars are used to assume ¨C What is the path of site-package ¨C 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 ¨C Interface to be used by implementation of import A little get off the import ¡ñ Plugin mechanism / Dynamically module load To be continued to later.....