Making your data strucutre more friendly using the "in" keyword

A thought recently occurred to me: Wouldn’t it be convenient to have a Tree object Tree() that supports the “in” keyword in Python? This way, I could simply do tree = Tree.from_list([1,2,3,4,5]) ... if val in tree: ... The good news is, we can actually do that! To make the class Tree compatible with the “in” method, we need to implement the __iter__ method. This method should recursively yield its children, enabling us to traverse the entire tree....

March 10, 2024

Python's Modules for Parallel Programming

Recently, I have been reviewing concurrent programming. Since I mainly use Python daily, I decided to learn by studying and practicing with it. This article does not touch on the principles and implementation of multithreading and its synchronization. There are many books, articles, and videos on the Internet. I am here mainly to discuss the modules provided in Python’s Standard Library and their usage. This article may be difficult to extract if you don’t understand threads and haven’t heard of the Producer–consumer problem....

December 10, 2022

The Floor Division and Modulus in Python

If you think // and % in Python would give you the same result as that in the static languages like C++ or Java, then you may be wrong about it. Here, I am going to explain it with C++. In C++, if you do cout << (167 / 12) << endl; The ouptut is 13, where the fractional part is discarded, even though the nature result 13.9166 is pretty close to 14, it just won’t round up....

October 22, 2022

Nginx, WSGI, Gevent, and Flask

Beginners are always obscured about why Flask needs Nginx and WSGI server and how much performance they increase. I used Flask for small projects that do not care much about production, so whether to use these frameworks was not a big problem for me. Recently, I’ve been working on some projects that required serious attention on them. After doing some research, I thought It was great to note it down....

September 18, 2022

Who Ate My Cheese

I saw this code no long ago lock = threading.Lock() # some code if some_condition: with lock: if some_condition: # some code The same condition checked twice before and after the lock aquired and released. It took me a while to think through this, and you’ll probably see something simular if you do coding with threads. Let me explain why is it. Imagine in a world, there are only Tom and Jerry...

May 29, 2021