Python features I didn't know about
Mo 04 September 2017Today I saw some code that showed me, that I not noticed some cool features since I joined the python universe.
Enum/Flags
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()
WHITE = RED | BLUE | GREEN
print(Color.RED in Color.WHITE) # True
print((Color.RED | Color.BLUE) in Color.WHITE) # True
print(Color.BLACK in Color.WHITE) # False
Zipapp
Python 3.5 introduces a new module zipapp which provides a simple way to create a zipped executable from python code.
Pygopar.com 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 __main__.py
__main__.py
can just use absolute imports likefrom ownmodule import hello
Project structure
root
|-- ownmodule
| |-- __init__.py
| |-- __main__.py # some startup code
| `-- hello.py # some code imported in __main__.py
|-- requirements.txt # list of dependencies
`-- zip_it.sh
zip_it.sh
#!/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 __main__.py to ./build/ which will be executed
mv ./build/ownmodule/__main__.py ./build/__main__.py
# 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 ```
Secrets
Python 3.6 introduces a new module secrets which provides strong random numbers generation for cryptography.