Python shenanigans

While refactoring one of my old scripts, I stumbled upon a weird thing about referencing in Python. Asked to one of my friends and it turned out to be a quite entertaining/depressing talk..

Here are some notes about Python which made me say “what in the..”:

Integers are objects, but some are special

a = 7

a is 7
> True

a = 300

a is 300
> False

Nonsense? Somehow. Turns out first between -5 and 256 (inclusive) the integer objects are predefined. So if you want to set a variable to it, it merely becomes a reference. Check this out:

a = 5

id(5)
> 139999587484016

id(a)
> 139999587484016 # <- Same object

a = 280 # <- You're allocating something new now

id(280)
> 139999546571984

id(a)
> 139999546557200 # <- Not anymore

Chained stuff

False == False in [False]
> True

Ehm. Excuse me?

Turns out this one is also not working like I thought. I was thinking this must be evaluated by a priority/order thing. Looks like that is equivalent to (False == False) and (False in [False]), so it makes sense 💡


Default variable doesn’t care about your mortal scope

Consider this function:

def tmp(a=[]):
    a.append('a')
    return a

As you can guess, if you call this without any argument it will return ['a']. But watch this:

tmp()
> ['a']

tmp()
> ['a', 'a']

tmp()
> ['a', 'a', 'a']

I don’t even question this one. Time to flip the table.


But wait, there are a lot more!

Do you know there is a dedicated repository which explains all of these, and more: WTF Python
I guess I’ll keep this as a bookmark and read slowly to keep myself calm.

C’ya 👋


Gürkan

python

285 Words

2022-07-22 00:24 +0200