SLIDE 1
José Manuel Ortega @jmortegac
PythonMemory Management101
DeepinginGarbagecollector
SLIDE 2 Aboutme
- @jmortegac
- http://jmortega.github.io
- https://www.linkedin.com/in/jmortega1/
SLIDE 3 Agenda
- Introductiontomemorymanagement
- Garbagecollectorandreference
countingwithpython
- Reviewthegcmoduleforconfiguring
thepythongarbagecollector
- Bestpracticesformemorymanagment
SLIDE 4 Introductiontomemorymanagement
- Memorymanagementistheprocessof
efficientlyallocating,de-allocating,and coordinatingmemorysothatallthe differentprocessesrunsmoothlyandcan
- ptimallyaccessdifferentsystem
resources.
SLIDE 5
PythonObjectsinMemory
SLIDE 6
PythonMemoryManager
SLIDE 7
Heapallocation
SLIDE 8 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()
Heapallocation
SLIDE 9 PythonObjectsinMemory
- EachvariableinPythonactsasanobject
- Pythonisadynamicallytypedlanguage
whichmeansthatwedonotneedto declaretypesforvariables.
SLIDE 10
PythonObjectsinMemory
SLIDE 11
PythonObjectsinMemory
SLIDE 12
PythonObjectsinMemory
SLIDE 13
PythonObjectsinMemory
SLIDE 14
id()method
SLIDE 15
id()method
SLIDE 16
id()method
SLIDE 17
isOperator
SLIDE 18 Referencecounting
- Pythonmanagesobjectsbyusingreference
counting
- Referencecountingworksbycountingthe
numberoftimesanobjectisreferencedby
- therobjectsintheapplication.
- Whenreferencestoanobjectareremoved,
thereferencecountforanobjectis decremented.
SLIDE 19
- Areferenceisacontainerobjectpointingat
anotherobject.
- Referencecountingisasimpletechnique
inwhichobjectsareallocatedwhenthereis referencetotheminaprogram
Referencecounting
SLIDE 20
- whenreferencecountincreases?
○ x=1 ○ def(x): ○ list.append(x)
Referencecounting
SLIDE 21
Referencecounting
SLIDE 22
Referencecounting
SLIDE 23
Referencecounting
SLIDE 24
- Easytoimplement
- Objectsareimmediatelydeletedwhen
referencecounteris0 ✗Notthread-safe ✗Doesn’tdetectcyclicreferences ✗spaceoverhead-referencecountis storedforeveryobject
Referencecounting
SLIDE 25
Garbagecollector(GC)module
SLIDE 26
- ReferenceCounting+GenerationalGC
- RefCountreacheszero,immediate
deletion
- Deletedobjectswithcyclicreferences
aredeletedwithTracingGC
PythonGarbagecollector
SLIDE 27
Garbagecollector(GC)referencecycle
SLIDE 28
>>> def ref_cycle(): ... list = [1, 2, 3, 4] ... list.append(list) ... return list
Garbagecollector(GC)referencecycle
SLIDE 29
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())
SLIDE 30
Garbage collector(GC) reference cycle
SLIDE 31 PythonObjectGraphs https://mg.pov.lt/objgraph/
import objgraph x = "hello" y = [x, [x], list(x), dict(x=x)]
filename='sample-graph.png')
SLIDE 32 Bestpracticesformemorymanagement
- Usinggc.collect()carefully
print("Collecting...") n = gc.collect() print("Number of unreachable objects collected:", n) print("Uncollectable garbage:", gc.garbage)
SLIDE 33
Garbage collector(GC) methods
SLIDE 34
- Usingwithcontextmanagerforworking
withfiles with open('data.txt', 'r') as file: data = ','.join(line.strip() for line in file)
Bestpracticesformemorymanagement
SLIDE 35
list= [1,2,3,4] list[1:3] list[slice(1,3)]
Bestpracticesformemorymanagement
SLIDE 36 Bestpracticesformemorymanagment
string= “hello” string+= “world” wordList = ("hello", "world") string = " ".join(wordList)
SLIDE 37
- UseIteratorsandGenerators
Bestpracticesformemorymanagement
SLIDE 38
- 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
References
SLIDE 39
https://www.youtube.com/c/JoseManuelOrtegadev