Accessing class variables from a list comprehension in the class definition

Class scope and list, set or dictionary comprehensions, as well as generator expressions do not mix. The why; or, the official word on this In Python 3, list comprehensions were given a proper scope (local namespace) of their own, to prevent their local variables bleeding over into the surrounding scope (see List comprehension rebinds names … Read more

How to strip all whitespace from string

Taking advantage of str.split’s behavior with no sep parameter: >>> s = ” \t foo \n bar ” >>> “”.join(s.split()) ‘foobar’ If you just want to remove spaces instead of all whitespace: >>> s.replace(” “, “”) ‘\tfoo\nbar’ Premature optimization Even though efficiency isn’t the primary goal—writing clear code is—here are some initial timings: $ python … Read more

Python 3.x rounding behavior

Python 3’s way (called “round half to even” or “banker’s rounding”) is considered the standard rounding method these days, though some language implementations aren’t on the bus yet. The simple “always round 0.5 up” technique results in a slight bias toward the higher number. With large numbers of calculations, this can be significant. The Python … Read more

Find column whose name contains a specific string

Just iterate over DataFrame.columns, now this is an example in which you will end up with a list of column names that match: import pandas as pd data = {‘spike-2’: [1,2,3], ‘hey spke’: [4,5,6], ‘spiked-in’: [7,8,9], ‘no’: [10,11,12]} df = pd.DataFrame(data) spike_cols = [col for col in df.columns if ‘spike’ in col] print(list(df.columns)) print(spike_cols) Output: … Read more

Concurrent.futures vs Multiprocessing in Python 3

I wouldn’t call concurrent.futures more “advanced” – it’s a simpler interface that works very much the same regardless of whether you use multiple threads or multiple processes as the underlying parallelization gimmick. So, like virtually all instances of “simpler interface”, much the same trade-offs are involved: it has a shallower learning curve, in large part … Read more

How to make an immutable object in Python?

Yet another solution I just thought of: The simplest way to get the same behaviour as your original code is Immutable = collections.namedtuple(“Immutable”, [“a”, “b”]) It does not solve the problem that attributes can be accessed via [0] etc., but at least it’s considerably shorter and provides the additional advantage of being compatible with pickle … Read more

What is a good practice to check if an environmental variable exists or not?

Use the first; it directly tries to check if something is defined in environ. Though the second form works equally well, it’s lacking semantically since you get a value back if it exists and only use it for a comparison. You’re trying to see if something is present in environ, why would you get just … Read more

Pinging servers in Python

If you don’t need to support Windows, here’s a really concise way to do it: import os hostname = “google.com” #example response = os.system(“ping -c 1 ” + hostname) #and then check the response… if response == 0: print hostname, ‘is up!’ else: print hostname, ‘is down!’ This works because ping returns a non-zero value … Read more

warning about too many open figures

Use .clf or .cla on your figure object instead of creating a new figure. From @DavidZwicker Assuming you have imported pyplot as import matplotlib.pyplot as plt plt.cla() clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched. plt.clf() clears the entire current figure with all its axes, … Read more