Dynamic Typing Interlude of Python

Python’s dynamic typing sometimes make people headache, but if you take some time to understand it, you will master it fast.

Here I give some simple samples to try to explain to you the key ideas on how python passes or references objects in between.

1) What happened behind each equal expression

When you do:

a = 3

This expression can be interpreted as:
a -> Name
= -> Reference
3 -> Object

Here 3 is an Object, which are pieces of allocated memory.

Each object has two standard header:

  1. Type designator
  2. Reference Counter

2) Shared References and In-Place Changes

a = 3
b = a
a = a + 2

In the code above, b will not change with a, because 3 is an integer object which is immutable!

However, if we do

a = [3,4]
b = a
a[0] = 2

at this time, b do change with a, because [3,4] is a list object which is mutable!

3) “is ” function can be used to test if both are reference to the same object:

L = [1,2,3]
M = L
L is M # true
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s