Python Gems

This post holds some Python® snippets of common and useful coding scenarios.

Iterate through Python List in Reverse

# Traverse Python list in reverse
for item in reversed(list_of_items):
    print(item)

Print List without brackets

mylist = [1,2,3,4]
print(mylist)
[1, 2, 3, 4]
print(','.join(map(str, mylist)))
1,2,3,4

Adding to lists

Subtly different to many other languages, you can use append, insert to add a single object (of any type) or extend, to add a list to another to form one contiguous list. If you use append to add a list, the whole list will be placed as a single object.

list1 = ['one', 'two']
list2 = ['three', 'four']
# Then extend the first with the second list
list1.extend(list2)
# to get
['one','two','three','four']
# If you instead had
list1.append(list2)
# it would become
['one', 'two', ['three','four']]

List manipulations

# Sort your list
list_sort = sorted(['z', 'a', 'f', 'b'])

Iterate through Dictionary

for key,value in mydictionary.items()
    print(key, value)

for key in mydictionary.keys()
    print(key, mydictionary[key])

for value in mydictionary.values()
    print(value)

Array of Formatted Strings

items = [1,2,3,4]
fstring_items = [f"the number: {i}" for i in items]
print(fstring_items)
['the number: 1', 'the number: 2', 'the number: 3', 'the number: 4']

List of Files in a Directory

directory = "/path/to/dir"
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]

Directory and File Detection

# Get the absolute path to this python file
current_path = os.path.dirname(os.path.abspath(__file__))

List Module Location

If you need to know where your current environment is getting a module from, then run python cli as below. Make sure you are in the correct environment. i.e if you are using a virtual environment, first activate it.

$ python3
>>> import module_name
>>> print(module_name.__file__)

Install from Repository

python3 -m pip install git+https://bitbucket.org/project-directory/repository.git@tag-or-branch-name

If you want to install globally use sudo.

If you get error error: invalid command 'bdist_wheel' then you need to install python -m pip wheel. This can likely happen in a virtual environment. You could add wheel as a dependency in your setup.py file.

Building your python package

For a long time to build a package the setup.py was called directly.

This is deprecated.

SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.

This docs page has a nice if detailed explanation.

In short replace your previous

python setup.py sdist bdist_wheel

with

python -m build

in the package directory containing the setup.py file.

Threading

What thread is that?

When dealing with thread’s inevitably you need to figure out what is what thread, which the name of the thread can help you with in debugging.

print(threading.current_thread().name, "your message")

Python ® is a registered trademark of the Python Software Foundation.