Docsity

Python Programming Slides, Slides of Programming Languages

Partial preview of the text

Download Python Programming Slides and more Slides Programming Languages in PDF only on Docsity!

VARIABLES ARE

MEMORY

REFERENCES

0x 100 0 0x 100 1 0x 100 2 0x 100 3 0x 100 4 0x 100 5 … Heap … object 1 object 2 object 3 Memory Address Python Memory Manager Memory

In Python, we can find out the memory address referenced by a variable by using the id() function. This will return a base-10 number. We can convert this base-10 number to hexadecimal, by using the hex() function.

Example

a = 10 print(hex(id(a)))

REFERENCE

COUNTING

Finding the Reference Count ctypes.c_long.from_address(address).value

sys.getrefcount(my_var)

passing my_var to getrefcount() creates an extra reference!

Here, we just pass the memory address (an

integer),

not a reference – does not affect reference count

Dynamic Typing

VS

Static Typing

Python, in contrast, is dynamically typed.

my_var = ‘ h e l l o ’ ;

The variable my_var is purely a reference to a string object with value hello. No type is “attached” to my_var.

my_var = 10;

The variable my_var is now pointing to an integer object with value 10. myVar String Hello

ref^ 0x

Int 10 0x

We can use the built-in type() function to determine the type of the object currently referenced by a variable. Remember: variables in Python do not have an inherent static type. Instead, when we call type(my_var) Python looks up the object my_var is referencing (pointing to), and returns the type of the object at that memory location.

my_var = 10 my_var in t 1 5 0x int 10 0x my_var = 15

my_var = 10

my_var

int 15 0x int 10 0x

my_var = my_var + 5

In fact, the value inside the int objects, can never be changed!

Consider an object in memory: type state (data) 0x

Changing the data inside

the object is called

modifying the internal state

of the object.

BankAccou nt Acct #: 12345 Balance: 150 0x BankAccount Acct #: 12345 Balance: 500 0x my_account

memory address has not changed

internal state (data) has changed

Object was mutated

fancy way of saying the internal data has changed

An object whose internal state can be changed, is called Mutable An object whose internal state cannot be changed, is called Immutable

t = (1, 2, 3) a = [1, 2] b = [3, 4] t = (a, b) But consider this: Lists are mutable: elements can be deleted, inserted, or replaced t = ([1, 2], [3, 4]) Tuples are immutable: elements cannot be deleted, inserted, or replaced In this case, both the container (tuple), and all its elements (ints) are immutable a.append(3) b.append(5) t =^ ([1,^ 2,^3 ],^ [3,^ 4,^5 ]) In this case, although the tuple is immutable, its elements are not. The object references in the tuple did not change but the referenced objects did mutate!

t = (1, 2, 3) tuple is immutable these are references to immutable object (int)

t = ([1, 2], [3, 4])

tuple is immutable these are references to a mutable object (list)