Python features I didn't know about

Today I saw some code that showed me, that I not noticed some cool features since I joined the python universe.


Python 3.4 introduces a new module called enum. Which provides Enum and Flag creation.

Enum example

from enum import Enum, auto

class Color(Enum):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

Flag example

from enum import Flag, auto
class Color(Flag):
    RED = auto()
    BLUE = auto()
    GREEN = auto()
    BLACK = auto()

print(Color.RED in Color.WHITE) # True
print((Color.RED | Color.BLUE) in Color.WHITE) # True
print(Color.BLACK in Color.WHITE) # False


Python 3.5 introduces a new module zipapp which provides a simple way to create a zipped executable from python code. provides a small example.

Because I had some problems with building a "fat" executable, I build a small script to pack my example app.

To support execution with: * dependencies * usage of your own code from can just use absolute imports like from ownmodule import hello

Project structure
|-- ownmodule
|   |--
|   |-- # some startup code
|   `-- # some code imported in
|-- requirements.txt # list of dependencies
#!/usr/bin/env bash

rm -rf ./build # clear build dir
mkdir ./build # create build dir

# install dependencies, but do not use os specific binary or compile to those
pip3 install --no-compile -U --no-binary all -r ./requirements.txt -t build

# copy own code into build
cp -R ./ownmodule ./build/

# move to ./build/ which will be executed
mv ./build/ownmodule/ ./build/

# create the executable archive
python3 -m zipapp build -o ownmodule.pyz -p "/usr/bin/env python3"

Now you can execute your project with ./ownmodule.pyz

If you face some issues with pip not able to install properly, use a virtualenv. That will solve the problem.

String interpolation

Python 3.6 introduces formatted string literals. Which supports string interpolation.

``` shell script a = "Hello" b= "World"

print(f"{a} {b}") # Hello World ```


Python 3.6 introduces a new module secrets which provides strong random numbers generation for cryptography.