potiongraphics potiongraphics - 4 months ago 8
Python Question

[Solved]: 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.

Update:

I wanted a way of adding ids easily and using = \ is not too much extra typing. The for loop adds hex values for each with leading zeros.

class IDS():
def __init__(self):
self.ID_MODE_STANDARD = \
self.ID_MODE_TILE = \
self.ID_MODE_MIRROR = \
None

for index,ID in enumerate(self.__dict__):
width = len(self.__dict__)
val = list("0x" + ("0" * width))
val[width - index + 1] = '1'
self.__dict__[ID] = int("".join(val),16)

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.