Python is a great programming language, as well as the most popular one according some statistics(e.g TIOBE Index). Its popularity has been only accelerating in recent years with the rise of AI/machine learning as Python has the richest set of APIs/Libraries in this space. As someone familiar/worked with a few different programming languages, I loved Python! It probably was the quickest learning curve for me to get used to with any programming language. Also, having the power of functional and object-oriented programming together made it much easier to write efficient and well-maintainable code. However, there are some “weird, not-so-obvious” behaviours in Python as well. Without caution/awareness, these behaviours often could make you scratching your head.
In this article, I have compiled a list of 5 such Python weird behaviours. Whether you are new to Python, or an experienced Python programmer, you might learn something new from this list. So, without further ado, let’s dive right in!
#1 Never use is for comparing primitives in Python:
Let’s start with a very simple Python code example as below:
a = 256print(a is 256)
# prints True Code language:PHP(php)
Works as expected. Now try once more:
b = 257print(b is 257)
# prints FalseCode language:PHP(php)
Hmm, doesn’t make any sense, right? Well, yeah, kind of. The moral of the story is to never use “is” for comparing primitives in Python. If you are interested in learning about the full story of why/how, please refer to this original article for a detailed explanation.
#Initializing a two-dimensional array in Python:
If you have some experience with Python already, you may have learned some useful and elegant shortcuts that the programming language offers. For example, initializing an array of four elements as below:
>>> a = [0]*4
>>> a
[0, 0, 0, 0]
>>> a[0]=2
>>> a
[2, 0, 0, 0]
Well, so far so good. What about and 2D array? Should work similarly, right? Interestingly, that’s where another Python weird behaviour shows up. Let’s try to initialize a 4X4 array:
Now, what’s that? TODO Here’s the StackOverflow answer where I first bumped into this, please refer to that if you are interested to learn more. Also, this article dives a bit deeper to explain the behaviour as well.
#3 Python weird behaviour with mutable default arguments:
In Python, default argument values are evaluated once when the function is defined, not each time the function is called. This can lead to unintended behaviour when using mutable default arguments like lists or dictionaries. Consider the following code sample:
The mutable object is shared between function calls, which may often lead to surprising/unexpected behaviour for developers coming from other languages and used to with default arguments like that.
#4 Duck Typing behaviour:
Python’s duck typing allows for method calls on objects without explicit type checks. For example, the following two classes (Duck and Person) if have the same method signature (named ‘quack’), can be called generically as if they were two inherited child classes from a common parent class.
class Duck:
def quack(self):
print("quack")
class Person:
def quack(self):
print("I'm quacking like a duck!")
def make_it_quack(obj):
obj.quack()
make_it_quack(Duck()) # quack
make_it_quack(Person()) # I'm quacking like a duck!
This can also lead to unexpected behaviour if not used with caution and/or handled carefully.
#5 Python Global Interpreter Lock (GIL):
Python’s Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously. This behaviour is unique to Python’s main implementation (CPython) and isn’t present in Java, Go, or C#. A simple Python example could be as below:
import threading
def print_numbers():
for i in range(5):
print(i)
t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_numbers)
t1.start()
t2.start()
Code language:JavaScript(javascript)
While you might expect multi-threading to improve performance, in Python, the GIL means that true parallelism (for CPU-bound tasks) isn’t possible with threads. In languages like Java or Go, threads can run truly in parallel on multiple cores, while Python’s GIL restricts this.
Conclusion:
So, that’s it for this article. Let me know by commenting down below if you liked them or not. Also, if you are aware of other Python weird behaviours that you think should have been on the list, feel free to share them below. Maybe I will add them in the future to this original list. Happy coding!
var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("%7B%22overlayOptions%22%3A%7B%22colorTheme%22%3A%22light%22%2C%22enableInfScroll%22%3Atrue%2C%22enableFilteringOpensOverlay%22%3Atrue%2C%22enablePostDate%22%3Atrue%2C%22enableSort%22%3Atrue%2C%22highlightColor%22%3A%22%23FFC%22%2C%22overlayTrigger%22%3A%22submit%22%2C%22resultFormat%22%3A%22expanded%22%2C%22showPoweredBy%22%3Atrue%2C%22defaultSort%22%3A%22relevance%22%2C%22excludedPostTypes%22%3A%5B%5D%7D%2C%22homeUrl%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%22%2C%22locale%22%3A%22en-US%22%2C%22postsPerPage%22%3A5%2C%22siteId%22%3A18994550%2C%22postTypes%22%3A%7B%22post%22%3A%7B%22singular_name%22%3A%22Post%22%2C%22name%22%3A%22Posts%22%7D%2C%22page%22%3A%7B%22singular_name%22%3A%22Page%22%2C%22name%22%3A%22Pages%22%7D%2C%22attachment%22%3A%7B%22singular_name%22%3A%22Media%22%2C%22name%22%3A%22Media%22%7D%7D%2C%22webpackPublicPath%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-content%5C%2Fplugins%5C%2Fjetpack%5C%2Fjetpack_vendor%5C%2Fautomattic%5C%2Fjetpack-search%5C%2Fbuild%5C%2Finstant-search%5C%2F%22%2C%22isPhotonEnabled%22%3Afalse%2C%22isFreePlan%22%3Atrue%2C%22apiRoot%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-json%5C%2F%22%2C%22apiNonce%22%3A%22155bc22a78%22%2C%22isPrivateSite%22%3Afalse%2C%22isWpcom%22%3Afalse%2C%22hasOverlayWidgets%22%3Afalse%2C%22widgets%22%3A%5B%5D%2C%22widgetsOutsideOverlay%22%3A%5B%5D%2C%22hasNonSearchWidgets%22%3Afalse%2C%22preventTrackingCookiesReset%22%3Afalse%7D"));
Leave a Reply