SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Import
     Andrew Svetlov
andrew.svetlov@gmail.com
  asvetlov.blogspot.com
Basics
●   Import statement
●   __import__ builtin
●   sys.path
●   WTF???
Import statement
●   import a.b.c
●   from a.b import c
●   from a.b import name
●   from ..b import c
●   from __future__ import absolute_import
+- a
    +- b <== current
        +- c
__import__
●   __import__(name:str, globals:dict=None,
    locals:dict=None, fromlist:list=(), level:int=0) ->
     Module
●   Returns module or toplevel package
    depending from fromlist.
Import lock
def f():
    from twisted.internet import reactor
    reactor.callLater(...)


●   Slow
●   Multithreading → Deadlock
Modules & Packages
●   __name__: str
●   __doc__: str
●   __file__: str
●   __path__: [str]
●   __package__: str
●   __cached__: str
●   __loader__: Loader
ABC
MetaPathFinder
MetaPathFinder      Loader


PathEntryFinder
PathEntryFinder         ResourceLoader


                        InspectLoader



   FileLoader
                             ExecutionLoader

 SourceLoader
sys.modules
●   'keyword': <module 'keyword' from '.../Lib/keyword.py'>
●   'unittest.signals': <module 'unittest.signals' from
    '…/Lib/unittest/signals.py'>
●   '_frozen_importlib': <module '_frozen_importlib' from
    '<frozen>'>
●   'sys': <module 'sys' (built-in)>
●   '_heapq': <module '_heapq' from '.../lib.linux-x86_64-3.3-
    pydebug/_heapq.cpython-33dm.so'>
Finder
●   MetaPathFinder
    –   find_module(fullname: str, path: str) -> Loader
    –   invalidate_caches()
●   PathEntryFinder
    –   find_loader(fullname: str) -> (Loader, str)
    –   invalidate_caches()
sys.meta_path
●   [Finder()]
    –   BuiltinImporter
    –   FrozenImporter
    –   PathFinder
sys.path_hooks
●   [callable(path:str) -> Finder]
    –   <class 'zipimport.zipimporter'>
    –   <function PathEntryFinder path_hook>


●   sys.path: [str]
●   sys.path_importer_cache: {str:Finder}
ABC
MetaPathFinder
MetaPathFinder      Loader
                     Loader

PathEntryFinder
PathEntryFinder         ResourceLoader
                        ResourceLoader


                        InspectLoader
                         InspectLoader



   FileLoader
    FileLoader
                              ExecutionLoader
                              ExecutionLoader
 SourceLoader
 SourceLoader
Loader
●   Base loader

●   load_module(fullname:str) -> Module
●   module_repr(module:Module) -> str
ResourceLoader(Loader)
●   Can return data from backend storage
●   load_module
●   get_data(path: str) -> bytes
>>> folder = os.path.dirname(__file__)
>>> resname = os.path.join(folder,
'image.png')
>>> __loader__.get_data(resname)
… <img bytes>
InspectLoader(Loader)
●   Introspection support
●   load_module
●   is_package(fullname:str) -> bool
●   get_code(fullname:str) -> CodeObject
●   get_source(fullname:str) -> str
ExecutionLoader(InspectLoader)
●   Support for execution modules as scripts
●   load_module, is_package, get_code,
    get_source
●   get_filename(fullname:str) -> str
    –   __file__
    –   Python -m package.module
FileLoader(ResourceLoader,
            ExecutionLoader)
●   Just to be. Sourceless loader
●   load_module, is_package, get_code,
    get_data, get_source, get_filename
SourceLoader(ResourceLoader,
          ExecutionLoader)
●   load_module, is_package, get_code,
    get_data, get_source, get_filename
●   path_mtime(path:str) -> int
●   path_stats(path:str) -> dict
    –   mtime:int
    –   size:int [optional]
●   set_data(path:str, data:bytes)
importlib
●   find_loader(name:str, path:str=None) ->
    Loader
●   import_module(name:str, package:str=None)
    -> Module
Bootstrap
●   site.py
●   venv
●   user sitepackages
    –   ~/.local/lib/python3.3/site-packages
●   site-packages
●   .pth files
●   sitecustomize.py
●   usersite.py
Shutdown
●   For every module in sys.modules set all global
    attrs to None
●   Delete modules
Вопросы?
     Andrew Svetlov
andrew.svetlov@gmail.com
  asvetlov.blogspot.com

Weitere ähnliche Inhalte

Was ist angesagt?

Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...
Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...
Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...mCloud
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt IIAjit Nayak
 
Compiler basics: lisp to assembly
Compiler basics: lisp to assemblyCompiler basics: lisp to assembly
Compiler basics: lisp to assemblyPhil Eaton
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part IAjit Nayak
 
Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Philip Zhong
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in goYusuke Kita
 
Mysql handle socket
Mysql handle socketMysql handle socket
Mysql handle socketPhilip Zhong
 
JavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyJavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyYasuharu Nakano
 
UE4 Tips and Tricks - Unreal Engine Toronto User Group - Meetup #2
UE4 Tips and Tricks - Unreal Engine Toronto User Group - Meetup #2UE4 Tips and Tricks - Unreal Engine Toronto User Group - Meetup #2
UE4 Tips and Tricks - Unreal Engine Toronto User Group - Meetup #2Robert Segal
 
Modern c++ Memory Management
Modern c++ Memory ManagementModern c++ Memory Management
Modern c++ Memory ManagementAlan Uthoff
 
Keeping track of uniques from streaming data with practically no memory! py...
Keeping track of uniques from streaming data with practically no memory!   py...Keeping track of uniques from streaming data with practically no memory!   py...
Keeping track of uniques from streaming data with practically no memory! py...Ali-Akber Saifee
 
Garbage collector in python
Garbage collector in pythonGarbage collector in python
Garbage collector in pythonIbrahim Kasim
 
Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsMichael Lehmann
 
CommonJS: JavaScript Everywhere
CommonJS: JavaScript EverywhereCommonJS: JavaScript Everywhere
CommonJS: JavaScript EverywhereKris Kowal
 
Java JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetJava JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetMark Papis
 
MongoDBで作るソーシャルデータ新解析基盤
MongoDBで作るソーシャルデータ新解析基盤MongoDBで作るソーシャルデータ新解析基盤
MongoDBで作るソーシャルデータ新解析基盤Takahiro Inoue
 
Python queue solution with asyncio and kafka
Python queue solution with asyncio and kafkaPython queue solution with asyncio and kafka
Python queue solution with asyncio and kafkaOndřej Veselý
 

Was ist angesagt? (20)

Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...
Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...
Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...
 
Murano docker demo
Murano docker demoMurano docker demo
Murano docker demo
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt II
 
Compiler basics: lisp to assembly
Compiler basics: lisp to assemblyCompiler basics: lisp to assembly
Compiler basics: lisp to assembly
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part I
 
Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in go
 
Mysql handle socket
Mysql handle socketMysql handle socket
Mysql handle socket
 
JavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyJavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovy
 
MongoDB Oplog入門
MongoDB Oplog入門MongoDB Oplog入門
MongoDB Oplog入門
 
UE4 Tips and Tricks - Unreal Engine Toronto User Group - Meetup #2
UE4 Tips and Tricks - Unreal Engine Toronto User Group - Meetup #2UE4 Tips and Tricks - Unreal Engine Toronto User Group - Meetup #2
UE4 Tips and Tricks - Unreal Engine Toronto User Group - Meetup #2
 
Modern c++ Memory Management
Modern c++ Memory ManagementModern c++ Memory Management
Modern c++ Memory Management
 
Arp
ArpArp
Arp
 
Keeping track of uniques from streaming data with practically no memory! py...
Keeping track of uniques from streaming data with practically no memory!   py...Keeping track of uniques from streaming data with practically no memory!   py...
Keeping track of uniques from streaming data with practically no memory! py...
 
Garbage collector in python
Garbage collector in pythonGarbage collector in python
Garbage collector in python
 
Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.js
 
CommonJS: JavaScript Everywhere
CommonJS: JavaScript EverywhereCommonJS: JavaScript Everywhere
CommonJS: JavaScript Everywhere
 
Java JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetJava JVM Memory Cheat Sheet
Java JVM Memory Cheat Sheet
 
MongoDBで作るソーシャルデータ新解析基盤
MongoDBで作るソーシャルデータ新解析基盤MongoDBで作るソーシャルデータ新解析基盤
MongoDBで作るソーシャルデータ新解析基盤
 
Python queue solution with asyncio and kafka
Python queue solution with asyncio and kafkaPython queue solution with asyncio and kafka
Python queue solution with asyncio and kafka
 

Ähnlich wie Import

Linux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloudLinux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloudAndrea Righi
 
Python import mechanism
Python import mechanismPython import mechanism
Python import mechanismYuki Nishiwaki
 
Introduction of unit test on android kernel
Introduction of unit test on android kernelIntroduction of unit test on android kernel
Introduction of unit test on android kernelJohnson Chou
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak PROIDEA
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLCommand Prompt., Inc
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLMark Wong
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLMark Wong
 
Go debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFxGo debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFxSignalFx
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 
Why you should be using structured logs
Why you should be using structured logsWhy you should be using structured logs
Why you should be using structured logsStefan Krawczyk
 
Semmle Codeql
Semmle Codeql Semmle Codeql
Semmle Codeql M. S.
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLCommand Prompt., Inc
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLMark Wong
 

Ähnlich wie Import (20)

Linux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloudLinux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloud
 
Python import mechanism
Python import mechanismPython import mechanism
Python import mechanism
 
Introduction of unit test on android kernel
Introduction of unit test on android kernelIntroduction of unit test on android kernel
Introduction of unit test on android kernel
 
Writing MySQL UDFs
Writing MySQL UDFsWriting MySQL UDFs
Writing MySQL UDFs
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
 
Lecture 04
Lecture 04Lecture 04
Lecture 04
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Linux device drivers
Linux device drivers Linux device drivers
Linux device drivers
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
Go debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFxGo debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFx
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Why you should be using structured logs
Why you should be using structured logsWhy you should be using structured logs
Why you should be using structured logs
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
 
Openstack 簡介
Openstack 簡介Openstack 簡介
Openstack 簡介
 
Semmle Codeql
Semmle Codeql Semmle Codeql
Semmle Codeql
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
Intro django
Intro djangoIntro django
Intro django
 

Mehr von Andrew Svetlov

Mehr von Andrew Svetlov (6)

Writing Open Source Library
Writing Open Source LibraryWriting Open Source Library
Writing Open Source Library
 
Asyncio
AsyncioAsyncio
Asyncio
 
Интерфейсы в Python
Интерфейсы в PythonИнтерфейсы в Python
Интерфейсы в Python
 
2056
20562056
2056
 
Py3k
Py3kPy3k
Py3k
 
2056
20562056
2056
 

Import

  • 1. Import Andrew Svetlov andrew.svetlov@gmail.com asvetlov.blogspot.com
  • 2. Basics ● Import statement ● __import__ builtin ● sys.path ● WTF???
  • 3. Import statement ● import a.b.c ● from a.b import c ● from a.b import name ● from ..b import c ● from __future__ import absolute_import +- a +- b <== current +- c
  • 4. __import__ ● __import__(name:str, globals:dict=None, locals:dict=None, fromlist:list=(), level:int=0) -> Module ● Returns module or toplevel package depending from fromlist.
  • 5. Import lock def f(): from twisted.internet import reactor reactor.callLater(...) ● Slow ● Multithreading → Deadlock
  • 6. Modules & Packages ● __name__: str ● __doc__: str ● __file__: str ● __path__: [str] ● __package__: str ● __cached__: str ● __loader__: Loader
  • 7. ABC MetaPathFinder MetaPathFinder Loader PathEntryFinder PathEntryFinder ResourceLoader InspectLoader FileLoader ExecutionLoader SourceLoader
  • 8. sys.modules ● 'keyword': <module 'keyword' from '.../Lib/keyword.py'> ● 'unittest.signals': <module 'unittest.signals' from '…/Lib/unittest/signals.py'> ● '_frozen_importlib': <module '_frozen_importlib' from '<frozen>'> ● 'sys': <module 'sys' (built-in)> ● '_heapq': <module '_heapq' from '.../lib.linux-x86_64-3.3- pydebug/_heapq.cpython-33dm.so'>
  • 9. Finder ● MetaPathFinder – find_module(fullname: str, path: str) -> Loader – invalidate_caches() ● PathEntryFinder – find_loader(fullname: str) -> (Loader, str) – invalidate_caches()
  • 10. sys.meta_path ● [Finder()] – BuiltinImporter – FrozenImporter – PathFinder
  • 11. sys.path_hooks ● [callable(path:str) -> Finder] – <class 'zipimport.zipimporter'> – <function PathEntryFinder path_hook> ● sys.path: [str] ● sys.path_importer_cache: {str:Finder}
  • 12. ABC MetaPathFinder MetaPathFinder Loader Loader PathEntryFinder PathEntryFinder ResourceLoader ResourceLoader InspectLoader InspectLoader FileLoader FileLoader ExecutionLoader ExecutionLoader SourceLoader SourceLoader
  • 13. Loader ● Base loader ● load_module(fullname:str) -> Module ● module_repr(module:Module) -> str
  • 14. ResourceLoader(Loader) ● Can return data from backend storage ● load_module ● get_data(path: str) -> bytes >>> folder = os.path.dirname(__file__) >>> resname = os.path.join(folder, 'image.png') >>> __loader__.get_data(resname) … <img bytes>
  • 15. InspectLoader(Loader) ● Introspection support ● load_module ● is_package(fullname:str) -> bool ● get_code(fullname:str) -> CodeObject ● get_source(fullname:str) -> str
  • 16. ExecutionLoader(InspectLoader) ● Support for execution modules as scripts ● load_module, is_package, get_code, get_source ● get_filename(fullname:str) -> str – __file__ – Python -m package.module
  • 17. FileLoader(ResourceLoader, ExecutionLoader) ● Just to be. Sourceless loader ● load_module, is_package, get_code, get_data, get_source, get_filename
  • 18. SourceLoader(ResourceLoader, ExecutionLoader) ● load_module, is_package, get_code, get_data, get_source, get_filename ● path_mtime(path:str) -> int ● path_stats(path:str) -> dict – mtime:int – size:int [optional] ● set_data(path:str, data:bytes)
  • 19. importlib ● find_loader(name:str, path:str=None) -> Loader ● import_module(name:str, package:str=None) -> Module
  • 20. Bootstrap ● site.py ● venv ● user sitepackages – ~/.local/lib/python3.3/site-packages ● site-packages ● .pth files ● sitecustomize.py ● usersite.py
  • 21. Shutdown ● For every module in sys.modules set all global attrs to None ● Delete modules
  • 22. Вопросы? Andrew Svetlov andrew.svetlov@gmail.com asvetlov.blogspot.com