Python Cheatsheet

ToString() for Classes
class ObjModel(object):

    def __init__(self):
        self.vertices = []

    def __str__(self):
        return str(self.vertices[5][0])
class ObjFaceType(Enum):
    TRIANGLE = 1
    UNKNOWN = 999
Create Enumeration-Value from Integer
detectedFaceType = ObjFaceType(999)
Compare Value to Enumeration
if (currentFaceType == ObjFaceType.UNKNOWN):
Switch over Enumeration-Values

There is no such feature!

Create a new Class
# as a .obj file contains several objects, the ObjModelContainer stores all those objects
class ObjModelContainer(object):

    def __init__(self):
        self.objects = []
Create a Instance of a Class
objAdapter = ObjAdapter()


Installing Python 3 on MacOS using homebrew

MacOS Systems come with python 2 preinstalled. Installing python 3 can be done using homebrew.

brew install python3
brew postinstall python3

Check for success using

python3 --version
pip3 -V

If brew complains that python3 is installed but not linked, use

brew link python

For me, linking failed with:

Warning: python 3.7.2 is already installed, it's just not linked
You can use `brew link python` to link this version.
MacBook-Pro:~ user$ brew link python
Linking /usr/local/Cellar/python/3.7.2... Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks

If the linking fails due to permission problems, you should read this thread.

They suggest a solution that entails creating and setting permissions on a folder:

sudo mkdir /usr/local/Frameworks

sudo chown $(whoami):admin /usr/local/Frameworks

Now try linking again, for me the link finally worked and python was available.

brew link python

python3 --version

Installing virtualenv

pip3 install virtualenv


Using virtualenv

Creation of a virtual environment:

$ virtualenv -p python3 <desired-path>

e.g. virtualenv -p python3 /home/user/dev/python/myproject/myenv

Activate the virtualenv:

$ source <desired-path>/bin/activate

e.g. source /home/user/dev/python/myproject/myenv/bin/activate

Deactivate the virtualenv:

$ deactivate