Originally published at pythoncircle.com
During the initial days as python programmer, all of us face some or other type of weird bug in our code ...
For further actions, you may consider blocking this person and/or reporting abuse
Ouch! This was quite surprising. It reminds me of old FORTRAN days when you could change the value of a constant. (FORTRAN passes everything by address, this means that if you want to pass a constant to a function, you need to write the constant somewhere and pass the address. If the function changes the parameter, the constant will change.)
Default arguments are evaluated only once. -> Mind blown. Does it mean one needs to keep track of if a function is called in the script already?
But just found a relevant SO discussion if someone interested. :-)
Great post, btw.
What's the thing about spaces and tabs? I mean okay I saw it already, that this is a harsh point for programmers, but why? (absolutely newbie here)
Bence,
Python doesn't support mixing tabs and spaces for indentation.
For other languages as well we should stick to one thing, either tab or spaces. This is because of different editors display tabs/spaces differently.
I'm pretty sure that python 2.7 allows mixed tabs and spaces (not that it is recommended) but python 3.x will error if you try that.
PEP 8 recommends spaces, but you can use tabs if that's what a project already uses.
python.org/dev/peps/pep-0008/#tabs...
Thanks for the reply. So I can use tabs or spaces as well but not in the same code, right?
Correct.
I consider myself fairly advanced in python, but I hadn't heard the term "interned" for strings. Thanks for pointing that out.
same here.
Thanks for sharing your knowledge.
Wait how is the last example true?? Lst is under the function scope only...
lst
is evaluated when the file is interpreted, hence it's always the same thing in memory. It's one of the gotchas of Python, you can see it here:As you can see
lst
points to the same object in memory.If you pass an argument it will substitute the one defined at evaluation time:
Notice how when I don't pass an external list as an argument, it starts using the default one.
The names are under function scope, but the values are stored as entries in a collection (tuple I think?) called
func_defaults
(__defaults__
in 3). It's attached to the function object, so I think that means it has the same scope as the declaration.Python 🙄
You are right in that it shouldn't happen as per the rules of the scope (variables defined within function scope should be destroyed once they leave that scope) but still, it happens! You can call it a bug of the cpython interpreter though the chances of falling in this trap is very less. You'll have to be careless enough to accept a default parameter and not handle its value at all in the function and just let it free (which is quite rare).