SlideShare a Scribd company logo
1 of 40
Download to read offline
José Manuel Ortega
@jmortegac
Python Memory
Management 101
Deeping in Garbage collector
About me
● @jmortegac
● http://jmortega.github.io
● https://www.linkedin.com/in/jmortega1/
Agenda
● Introduction to memory management
● Garbage collector and reference counting
with python
● Review the gc module for configuring the
python garbage collector
● Best practices for memory managment
Introduction to memory management
● Memory management is the process of
efficiently allocating, de-allocating, and
coordinating memory so that all the
different processes run smoothly and can
optimally access different system
resources.
Python Objects in Memory
Python Memory Manager
Heap allocation
Heap allocation
def main():
x=300
print(id(x))
w=fun(x)
print(id(w))
def sqr(x):
print (id(x))
z=x*x
print(id(z))
return z
if __name__ == "__main__":
main()
Python Objects in Memory
● Each variable in Python acts as an object
● Python is a dynamically typed language
which means that we do not need to
declare types for variables.
Python Objects in Memory
Python Objects in Memory
Python Objects in Memory
Python Objects in Memory
id() method
id() function
id() function
Is Operator
Reference counting
● Python manages objects by using reference
counting
● Reference counting works by counting the
number of times an object is referenced by
other objects in the application.
● When references to an object are removed,
the reference count for an object is
decremented.
Reference counting
● A reference is a container object pointing at
another object.
● Reference counting is a simple technique
in which objects are allocated when there is
reference to them in a program
Reference counting
● when reference count increases?
○ x=1
○ def(x):
○ list.append(x)
Reference counting
Reference counting
Reference counting
Reference counting
● Easy to implement
● Objects are immediately deleted when
reference counter is 0
✗ Not thread-safe
✗ Doesn’t detect cyclic references
✗ space overhead - reference count is
stored for every object
Python Garbage collector
● The Python Garbage Collector (GC) runs
during the program execution and is
triggered if the reference count reduces to
zero.
Garbage collector(GC) module
Python Garbage collector
● Reference Counting + Generational GC
● RefCount reaches zero, immediate
deletion
● Deleted objects with cyclic references
are deleted with Tracing GC
Garbage collector(GC) reference cycle
Garbage collector(GC) reference cycle
>>> def ref_cycle():
... list = [1, 2, 3, 4]
... list.append(list)
... return list
Garbage collector(GC) reference cycle
import gc
for i in range(8):
ref_cycle()
n = gc.collect()
print("Number of unreachable objects collected by GC:", n)
print("Uncollectable garbage:", gc.garbage)
print("Number of unreachable objects collected by GC:",
gc.collect())
Garbage collector(GC) reference cycle
Python Object Graphs
https://mg.pov.lt/objgraph/
>>> x = []
>>> list = [x, [x], dict(x=x)]
>>> import objgraph
>>> objgraph.show_refs([y],
filename='sample-graph.png')
Best practices for memory managment
● Using gc.collect() carefully
print("Collecting...")
n = gc.collect()
print("Number of unreachable objects collected:", n)
print("Uncollectable garbage:", gc.garbage)
Best practices for memory managment
● Using with context manager for working
with files
with open('data.txt', 'r') as file:
data = ','.join(line.strip() for line in file)
Best practices for memory managment
● Avoid List Slicing with [:]
list= [1,2,3,4]
list[1:3]
list[slice(1,3)]
Best practices for memory managment
● String Concatenation
string= “hello”
string+= “world”
wordList = ("hello", "world")
string = " ".join(wordList)
Best practices for memory managment
● Use Iterators and Generators
References
● https://stackabuse.com/basics-of-memory-management-in-p
ython/
● https://realpython.com/python-memory-management
● https://rushter.com/blog/python-garbage-collector
● https://pythonchb.github.io/PythonTopics/weak_references.
html
https://www.youtube.com/c/JoseManuelOrtegadev
https://speakerdeck.com/jmortega

More Related Content

What's hot

What's hot (20)

กลุ่ม6
กลุ่ม6กลุ่ม6
กลุ่ม6
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time Checks
 
Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11
 
Coding convention
Coding conventionCoding convention
Coding convention
 
Java & OOP Core Concept
Java & OOP Core ConceptJava & OOP Core Concept
Java & OOP Core Concept
 
関数プログラマから見たPythonと機械学習
関数プログラマから見たPythonと機械学習関数プログラマから見たPythonと機械学習
関数プログラマから見たPythonと機械学習
 
building global software/earthcube->sciencecloud
building global software/earthcube->sciencecloudbuilding global software/earthcube->sciencecloud
building global software/earthcube->sciencecloud
 
Reactive x
Reactive xReactive x
Reactive x
 
Functional Programming, simplified
Functional Programming, simplifiedFunctional Programming, simplified
Functional Programming, simplified
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 
Openstack 簡介
Openstack 簡介Openstack 簡介
Openstack 簡介
 
Example.cs
Example.csExample.cs
Example.cs
 
Openstack taskflow 簡介
Openstack taskflow 簡介Openstack taskflow 簡介
Openstack taskflow 簡介
 
Richard Salter: Using the Titanium OpenGL Module
Richard Salter: Using the Titanium OpenGL ModuleRichard Salter: Using the Titanium OpenGL Module
Richard Salter: Using the Titanium OpenGL Module
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
 
Using VI Java from Scala
Using VI Java from ScalaUsing VI Java from Scala
Using VI Java from Scala
 
Java JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetJava JVM Memory Cheat Sheet
Java JVM Memory Cheat Sheet
 
Gopher conbr golang e data science - oficial
Gopher conbr   golang e data science - oficialGopher conbr   golang e data science - oficial
Gopher conbr golang e data science - oficial
 
Lab 1
Lab 1Lab 1
Lab 1
 
RecSplit Minimal Perfect Hashing
RecSplit Minimal Perfect HashingRecSplit Minimal Perfect Hashing
RecSplit Minimal Perfect Hashing
 

Similar to Python memory managment. Deeping in Garbage collector

Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
krmboya
 

Similar to Python memory managment. Deeping in Garbage collector (20)

Garbage collector in python
Garbage collector in pythonGarbage collector in python
Garbage collector in python
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Python高级编程(二)
Python高级编程(二)Python高级编程(二)
Python高级编程(二)
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The Basics
 
Functional python
Functional pythonFunctional python
Functional python
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 
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 GC
Python GCPython GC
Python GC
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
Python for PHP developers
Python for PHP developersPython for PHP developers
Python for PHP developers
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
Take advantage of C++ from Python
Take advantage of C++ from PythonTake advantage of C++ from Python
Take advantage of C++ from Python
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Dafunctor
DafunctorDafunctor
Dafunctor
 
Transitioning to Native
Transitioning to NativeTransitioning to Native
Transitioning to Native
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
 

More from Jose Manuel Ortega Candel

Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops
Jose Manuel Ortega Candel
 

More from Jose Manuel Ortega Candel (20)

Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdfAsegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
 
PyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdfPyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdf
 
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
 
Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops
 
Evolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdfEvolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdf
 
Implementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdfImplementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdf
 
Computación distribuida usando Python
Computación distribuida usando PythonComputación distribuida usando Python
Computación distribuida usando Python
 
Seguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloudSeguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloud
 
Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud
 
Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python
 
Sharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8sSharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8s
 
Implementing cert-manager in K8s
Implementing cert-manager in K8sImplementing cert-manager in K8s
Implementing cert-manager in K8s
 
Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)
 
Python para equipos de ciberseguridad
Python para equipos de ciberseguridad Python para equipos de ciberseguridad
Python para equipos de ciberseguridad
 
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodanShodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
 
ELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue TeamELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue Team
 
Monitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source toolsMonitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source tools
 
SecDevOps containers
SecDevOps containersSecDevOps containers
SecDevOps containers
 
Machine Learning para proyectos de seguridad(Pycon)
Machine Learning para proyectos de seguridad(Pycon)Machine Learning para proyectos de seguridad(Pycon)
Machine Learning para proyectos de seguridad(Pycon)
 
Machine learning para proyectos de seguridad
Machine learning para proyectos de seguridadMachine learning para proyectos de seguridad
Machine learning para proyectos de seguridad
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

Python memory managment. Deeping in Garbage collector