potiongraphics potiongraphics - 3 months ago 10
Python Question

Python: How can I access IDs separated by | (pipe) in an argument

I have searched both here and using google. The | (pipe) symbol is the bitwise OR operator, but I can't find anything specific to my problem. Here is an example from the Cinema4D Python SDK and has an argument flags where you can set multiple IDs separated by the | symbol.

What is this specifically and how do I access the IDs in the function below?

ID_OK = 100
ID_CANCEL = 101

def Func(flags):
print flags
return

Func(ID_OK|ID_CANCEL)

..

>> 101


Thank you.

Answer

Flags like this are sometimes called "bit-masks". If you define them as hexadecimal you will find them much easier to use.

You can use binary & to determine if the flag is set. For example:

ID_OK = 0x01
ID_CANCEL = 0x10

def Func(flags):
    print "0x%02x" % (flags)
    if flags & ID_OK:
        print "ID_OK"
    if flags & ID_CANCEL:
        print "ID_CANCEL"

    print
    return

Func(ID_OK)
Func(ID_CANCEL)
Func(ID_OK|ID_CANCEL)

Gives:

0x01
ID_OK

0x10
ID_CANCEL

0x11
ID_OK
ID_CANCEL

Flags are usually larger than this. If you have a small number of flags then it is much simpler if you can reserve one nybble for each flag.