Week4 Class1
Week4 Class1
• Dynamic Typing
• Variable, Objects and references
• Garbage collection
• Shared references and in-place changes
• Equality of objects
Dynamic Typing:
• Variables are entries in a system table, with spaces for links to objects.
• Objects are pieces of allocated memory, with enough space to represent the values for which they stand.(Each
object also has two standard header fields: a type designator used to mark the type of the object, and a reference
counter used to determine when it’s OK to reclaim the object)
• References are automatically followed pointers from variables to objects.
Objects Are Garbage-Collected:
>> a=5
>> a =‘anoop’
What happens to object 5??
• In Python, whenever a name is assigned to a new object, the space held by the prior object is reclaimed if it is not referenced
by any other name or object. This automatic reclamation of objects’ space is known as garbage collection
• Internally, Python accomplishes this by keeping a counter in every object that keeps track of the number of references
currently pointing to that object. As soon as (and exactly when) this counter drops to zero, the object’s memory space is
automatically reclaimed.
Shared references:
>> a = 3
>> b =a
• This scenario in Python—with multiple names referencing the same object—is usually called a shared reference
• The names a and b are not linked to each other directly when this happens
• There is no way to ever link a variable to another variable in Python. Rather, both variables point to the same
object via their references.
>>> a = 3
>>> b = a
>>> a = 'spam’
Shared References and In-Place Changes:
Python’s mutable types, including lists, dictionaries, and sets. For instance, an assignment to an offset in a list actually
changes the list object itself in place, rather than generating a brand-new list object.
>>> L1 = [2, 3, 4]
>>> L2 = L1
>>> L1 = 24
>>> L = [1, 2, 3]
>>> M = [1, 2, 3] # M and L reference different objects
>>> L == M # Same values
True
>>> L is M # Different objects
False
Shared References and Equality:
>>> X = 42
>>> Y = 42 # Should be two different objects
>>> X == Y
True
>>> X is Y # Same object anyhow: caching at work!
True
• Because small integers and strings are cached and reused, though, is tells us they reference the same
single object.
How to check number of references??
>>> import sys
>>> sys.getrefcount(1)