SlideShare a Scribd company logo
Materials @ h ps://github.com/prodicus/talks
Demys fying how imports
work in Python
Tasdik Rahman (@tasdikrahman)
Presented @ ChennaiPy, October'16 meetup
Requirements
Python 3.4 or newer.
No extra 3rd party extensions needed.
Coming over for this meetup!
2
Modules
Any  python source file would be counted as a
module.
You import a module to execute and access its
classes, func on defini ons, a ributes.
>>> import os 
>>> os.path.abspath('.') 
'/home/tasdik/Dropbox/talks/chennaipy/october/samplecode' 
>>>  
posixpath would be the module name where the
method  abspath() resides.  posixpath being the
alias name for  os.path in linux systems. 3
What happens when you import a module?
It being a python script, the statements start
ge ng executed from top to bo om of the
source file.
If there are any tasks in the statements ( eg: a 
print() statement ), then they get executed
when the module is being imported.
# 'samplecode/basicpackage/' 
>>> import basicpackage.bar 
inside basicpackage/__init__.py 
inside 'basicpackage/bar' 
>>> 
4
Packages
Used to orgranize larger number of modules in a
systema c manner.
One way of accessing individual modules is using
the  import foo.bar import style.
# typical package structuring 
$ tree basicpackage/ 
basicpackage 
├── bar.py 
├── foo.py 
└── __init__.py 
5
Why packages?
bumblebee 
├── constants.py 
├── core.py 
├── exceptions.py 
├── helpers 
│   ├── __init__.py 
│   └── vwo_helpers.py 
├── __init__.py 
└── vwo 
    ├── __init__.py 
    └── smart_code.py 
Looks good?
6
Different styles for impor ng
modules
7
from module import foo
This essen ally imports the module first then
picks up specific parts from the module to be
available locally.
>>> from basicpackage import foo
inside basicpackage/__init__.py 
inside 'basicpackage/foo.py' with a variable in it 
>>> 
allows using the parts of the module without
giving the full prefix before it.
8
from module import *
Brings out all the symbols from the module and
makes them available in the namespace.
>>> from basicpackage_all import * 
inside basicpackage_all/__init__.py 
inside 'basicpackage_all/foo.py' with a variable in it 
inside 'basicpackage_all/bar.py'
>>> 
You can use  __all__ inside your  __init__.py
module to import the modules which you need.
Generally not a good idea! Namespace collisions
can occur.
9
Takeaways so far
The way you import a module doesn't actually
change the working of the module.
Difference between 
import foo.bar and  from foo import bar ?
the difference is subjec ve. Pick one style and
be consistent with it.
doing a  from foo import bar is more efficient.
python imports the whole file! period.
10
Module names
naming modules follow the general variable
naming conven on.
# Bad choices 
$ touch 2foo.py MyAwesomeFoo.py os.py 
 
# Good choices 
$ touch foo.py a_large_module_name.py 
Don't use Non‐ASCII characters while doing so.
Avoid crea ng module names which conflict with
the standard library modules.
11
Module lookup
If it's not in the python path, it just won't import.
>>> pprint(sys.path) 
['', 
 '/usr/lib/python35.zip', 
 ... 
 '/usr/lib/python3/dist­packages'] 
 
Explicitly bring a module inside your path
>>> import sys 
>>> sys.path.append('/absoule/path/to/module') 
12
Modules get imported Only once!
13
But I really want to import it again!
>>> from importlib import reload
>>> reload(foo) 
This is generally not recommended!
If you do so, zombies will spawn.
No really!
14
Implicit Rela ve imports
$ rod/ 
    foo.py 
    bar.py 
    __init__.py 
So want to have some things from  foo.py inside 
bar.py ? Nothing uncommon.
# python 2 
# inside "bar.py" 
import foo 
Don't do it! Works in  python2 but doesn't work in 
python3 15
How do I fix it?
16
Absolute rela ve imports
One way to fix it would be using the name of it's
top level package name  relativeimports.
# relativeimports/foo.py 
from relativeimports import bar 
 
This works, but is bri le!
What if you wanted to change the name of the
top level package?
Errors!!!!
17
Explicit rela ve imports
A be er way would be to
# explicitimports/bar.py 
from . import foo 
Works even when you rename the root level
package for whatever the reason may be 
(eg: you renamed it to  explicitimports_v1_0 )
$ mv explicitimports/ newimports/ 
18
The leading (.) would be used to move up a
directory.
# look for foo.py in the same level 
from . import foo   
 
# go a dir up and import foo.py 
from .. import foo   
 
# go a dir up and enter plino/ and look for bar.py 
from ..plino import bar   
19
__init__.py
20
What should you put into it?
Most of the  me, it's empty!
S ching together submodules:
# minions/foo.py 
class Foo(object): 
  pass 
 
# minions/bar.py 
class Bar(object): 
  pass 
     
# minions/__init__.py 
from .foo import Foo 
from .bar import Bar 
     
21
Advantage?
Headache free imports for small modules
>>> import minions 
inside minions/__init__.py 
inside 'minions/foo.py' with a variable in it 
inside 'minions/bar.py' 
>>> a = minions.Foo() 
>>> b = minions.Bar() 
controlling import behaviour of  from foo import *
using the  __all__ variable inside  __init__.py
22
Performance anybody?
Should I put the whole python package inside the
__init__.py?
Yes. If it's small!
Not a good idea if you have a very large project!
23
References
h ps://docs.python.org/3/tutorial/modules.html
h ps://docs.python.org/3/reference/import.html
h ps://docs.python.org/3/reference/execu onm
odel.html
h ps://docs.python.org/3/library/distribu on.ht
ml
24
Ques ons?
Would be happy to answer them!
h p://tasdikrahman.me/
Twi er (@tasdikrahman)
Github (@prodicus)
25

More Related Content

PDF
Python Crash Course
PDF
web programming Unit VIII complete about python by Bhavsingh Maloth
PDF
Python tutorial
PPT
Python - Introduction
PPTX
Learn python – for beginners
PDF
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
PPTX
Python Libraries and Modules
PDF
Beginning Python
Python Crash Course
web programming Unit VIII complete about python by Bhavsingh Maloth
Python tutorial
Python - Introduction
Learn python – for beginners
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Python Libraries and Modules
Beginning Python

What's hot (19)

PPTX
Best Python Online Training with Live Project by Expert
PDF
Python final ppt
PDF
Introduction to python
PPTX
Introduction to-python
PPT
Learn python
PPTX
Introduction Jupyter Notebook
PPT
Python ppt
PDF
Intro to Python for Non-Programmers
PDF
Doing the Impossible
PDF
Introduction to python 3 2nd round
PPTX
Python libraries for data science
PDF
Python 3.5: An agile, general-purpose development language.
PDF
Introduction to python 3
PPTX
Introduction to Jupyter notebook and MS Azure Machine Learning Studio
PDF
Python quick guide1
PPT
PDF
The Benefits of Type Hints
PPTX
Sour Pickles
PDF
Python Workshop
Best Python Online Training with Live Project by Expert
Python final ppt
Introduction to python
Introduction to-python
Learn python
Introduction Jupyter Notebook
Python ppt
Intro to Python for Non-Programmers
Doing the Impossible
Introduction to python 3 2nd round
Python libraries for data science
Python 3.5: An agile, general-purpose development language.
Introduction to python 3
Introduction to Jupyter notebook and MS Azure Machine Learning Studio
Python quick guide1
The Benefits of Type Hints
Sour Pickles
Python Workshop
Ad

Viewers also liked (20)

PDF
Designing Modules in Python
ODP
Pythonpresent
PDF
1. anexo i contrato de prestação de serviços
PDF
업사이클 완성
DOC
Anexo II - Termo de referência
PPTX
14185398 조하경 창발
PDF
Sales Outsourcing Factsheet
PPTX
Upcycling2
PPTX
Agriculture, Food Security and Health
PPTX
Vuoden 2017 eläkeuudistus - kansalaisten käsitykset ja eläkeinfon merkitys
PDF
Postgresql + Python = Power!
PDF
Education and skill development
PDF
망고스틴
PPTX
Introduction to the basics of Python programming (part 3)
PDF
OSINT tools for security auditing [FOSDEM edition]
PPTX
사이트 링크 리더 검증
PDF
창발 업사이클링
PDF
Programando em python modulos
PPTX
(Some-)viestintä osana asiantuntijoiden työtä - "Työeläketietäjät tulessa"
PPTX
Työeläkeindikaattorit 2016
Designing Modules in Python
Pythonpresent
1. anexo i contrato de prestação de serviços
업사이클 완성
Anexo II - Termo de referência
14185398 조하경 창발
Sales Outsourcing Factsheet
Upcycling2
Agriculture, Food Security and Health
Vuoden 2017 eläkeuudistus - kansalaisten käsitykset ja eläkeinfon merkitys
Postgresql + Python = Power!
Education and skill development
망고스틴
Introduction to the basics of Python programming (part 3)
OSINT tools for security auditing [FOSDEM edition]
사이트 링크 리더 검증
창발 업사이클링
Programando em python modulos
(Some-)viestintä osana asiantuntijoiden työtä - "Työeläketietäjät tulessa"
Työeläkeindikaattorit 2016
Ad

Similar to Demystifying how imports work in Python (20)

PDF
Python Imports
PPTX
Python for Beginners
PDF
Modules and Packages in Python_Basics.pdf
PPTX
Class 12 CBSE Chapter: python libraries.pptx
PDF
Using Python Libraries.pdf
PPT
Python modules
PPTX
Chapter 03 python libraries
PPT
py lsfgsdfgdsfgdfsgdsfgdfsfdgfdlecasdf.ppt
PPTX
Modules,Packages,Librarfrserrrrrrrrrrrries.pptx
PPT
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
PPT
jb_Modules_in_Python.ppt
PDF
Python Course Functions and Modules Slides
PDF
Modules 101
PPTX
Modules and Packages in Python Programming Language.pptx
PPTX
Python Session - 5
PDF
Python. libraries. modules. and. all.pdf
PPTX
packages.pptx
PPTX
7-_Modules__Packagesyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.pptx
PPTX
Learn python in 20 minutes
PPTX
Using-Python-Libraries.9485146.powerpoint.pptx
Python Imports
Python for Beginners
Modules and Packages in Python_Basics.pdf
Class 12 CBSE Chapter: python libraries.pptx
Using Python Libraries.pdf
Python modules
Chapter 03 python libraries
py lsfgsdfgdsfgdfsgdsfgdfsfdgfdlecasdf.ppt
Modules,Packages,Librarfrserrrrrrrrrrrries.pptx
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
jb_Modules_in_Python.ppt
Python Course Functions and Modules Slides
Modules 101
Modules and Packages in Python Programming Language.pptx
Python Session - 5
Python. libraries. modules. and. all.pdf
packages.pptx
7-_Modules__Packagesyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.pptx
Learn python in 20 minutes
Using-Python-Libraries.9485146.powerpoint.pptx

Recently uploaded (20)

PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
history of c programming in notes for students .pptx
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
AI in Product Development-omnex systems
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Introduction to Artificial Intelligence
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
System and Network Administration Chapter 2
PDF
Nekopoi APK 2025 free lastest update
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
top salesforce developer skills in 2025.pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Understanding Forklifts - TECH EHS Solution
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
wealthsignaloriginal-com-DS-text-... (1).pdf
Navsoft: AI-Powered Business Solutions & Custom Software Development
history of c programming in notes for students .pptx
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
AI in Product Development-omnex systems
Operating system designcfffgfgggggggvggggggggg
Introduction to Artificial Intelligence
Design an Analysis of Algorithms I-SECS-1021-03
System and Network Administration Chapter 2
Nekopoi APK 2025 free lastest update
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Which alternative to Crystal Reports is best for small or large businesses.pdf
Softaken Excel to vCard Converter Software.pdf
Odoo Companies in India – Driving Business Transformation.pdf
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
CHAPTER 2 - PM Management and IT Context
top salesforce developer skills in 2025.pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Understanding Forklifts - TECH EHS Solution

Demystifying how imports work in Python