Accessing class variables from a list comprehension in the class definition

How do you access other class variables from a list comprehension within the class definition? The following works in Python 2 but fails in Python 3: class Foo: x = 5 y = [x for i in range(1)] Python 3.2 gives the error: NameError: global name ‘x’ is not defined Trying Foo.x doesn’t work either. … Read more

How to make an immutable object in Python?

Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can’t just override __setattr__, because then you can’t even set attributes in the __init__. Subclassing a tuple is a trick that works: class Immutable(tuple): def __new__(cls, a, b): return tuple.__new__(cls, (a, b)) @property … Read more

multiprocessing vs multithreading vs asyncio in Python 3

I found that in Python 3.4 there are few different libraries for multiprocessing/threading: multiprocessing vs threading vs asyncio. But I don’t know which one to use or is the “recommended one”. Do they do the same thing, or are different? If so, which one is used for what? I want to write a program that … Read more

Type hinting a collection of a specified type

Using Python 3’s function annotations, it is possible to specify the type of items contained within a homogeneous list (or other collection) for the purpose of type hinting in PyCharm and other IDEs? A pseudo-python code example for a list of int: def my_func(l:list<int>): pass I know it’s possible using Docstring… def my_func(l): “”” :type … Read more