Understanding slicing

I need a good explanation (references are a plus) on Python slicing. 3 34 It’s pretty simple really: a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 a[:] # a copy of the whole array There is also the step … Read more

Difference between staticmethod and classmethod

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod? 3 33 Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo: class A(object): def foo(self, x): print(f”executing foo({self}, {x})”) @classmethod def class_foo(cls, x): print(f”executing class_foo({cls}, {x})”) @staticmethod def static_foo(x): … Read more

How can I safely create a nested directory?

What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: import os file_path = “/my/directory/filename.txt” directory = os.path.dirname(file_path) try: os.stat(directory) except: os.mkdir(directory) f = file(filename) Somehow, I missed os.path.exists (thanks kanja, Blair, … Read more

How do I execute a program or call a system command?

How do I call an external command within Python as if I’d typed it in a shell or command prompt? 6 63 Use the subprocess module in the standard library: import subprocess subprocess.run([“ls”, “-l”]) The advantage of subprocess.run over os.system is that it is more flexible (you can get the stdout, stderr, the “real” status … Read more

How do I merge two dictionaries in a single expression (take union of dictionaries)?

I want to merge two dictionaries into a new dictionary. x = {‘a’: 1, ‘b’: 2} y = {‘b’: 10, ‘c’: 11} z = merge(x, y) >>> z {‘a’: 1, ‘b’: 10, ‘c’: 11} Using x.update(y) modifies x in-place instead of creating a new dictionary. I also want the last-one-wins conflict-handling of dict.update() as well. … Read more