Question

I have this set of constants declarations

    self.POUTPUT = 1
    self.PPWM = 2
    self.PINPUT = 4
    self.PUNUSED = 8
    self.PSONAR = 16
    self.PULTRA = 32
    self.PSERVOD = 64
    self.PSTEPPER = 128
    self.PCOUNT = 256
    self.PINPUTDOWN = 512
    self.PINPUTNONE = 1024

What is the pythonic way of checking whether a value matches any of the input states (4,512 and 1024) please? Extra info: I'd normally just use bit pattern checking in simpler languages but I wondered if there was a better way in Python :) Basically it is that each pin can have one of the I/O states above but if a pin is any of of the input values then one action occurs e.g if pin == 4 or 512 or 1024 -> do something

Was it helpful?

Solution 2

Testing for set membership (which is what you seem to be doing) is best done using a set.

self.input_states = {self.PINPUT, self.PINPUTDOWN, self.PINPUTNONE}

# later
if value in self.input_states:
    do_something()

Of course you could handle this in a variety of essentially-identical ways, but one way or another you have to encode some knowledge as to which of these magic numbers are "input states".


Now if, as has been suggested, what you actually want is to do some bit-masking or tests based on whether a particular bit is set, then you want to take a look at the Python bitwise operators. In particular, to see if a value is equal to one of the ones you've got there, you'd use the bitwise and, which is denoted by & in Python. Joran's answer covers this use well, but the basic idea is:

if value & self.PINPUT: # Value has a 1 in the PINPUT bit (bit 3)
    do_something()

Or if all of those input values trigger the same action:

if any(value & p for p in (self.PINPUT, self.PINPUTDOWN, self.PINPUTNONE)):
    do_something()

OTHER TIPS

if SOME_DATA & self.PINPUTNONE:  # do somethign

is how people usually do it

to check alot

ANY = self.POUTPUT | self.PPWM | self.PINPUT | self.PUNUSED |  self.PSONAR  ...
if some_data & ANY: #do something
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top