Checking if a variable belongs to a class in python
You could use the __dict__
property which composes a class, for example:
In [1]: class Foo(object):
...: bar = "b"
...: zulu = "z"
...:
In [2]: "bar" in Foo.__dict__
Out[2]: True
Or as you're searching for the values use __dict__.values()
:
In [3]: "b" in Foo.__dict__.values()
Out[3]: True
As Peter Wood points out, the vars()
built-in can also be used to retrieve the __dict__
:
In [12]: "b" in vars(Foo).values()
Out[12]: True
The __dict__
property is used as a namespace for classes and so will return all methods, magic methods and private properties on the class as well, so for robustness you might want to modify your search slightly to compensate.
In your case, you might want to use a classmethod
, such as:
class States(object):
ALABAMA = "AL"
FLORIDA = "FL"
@classmethod
def is_state(cls, to_find):
print(vars(cls))
states = [val for key, val in vars(cls).items()
if not key.startswith("__")
and isinstance(val, str)]
return to_find in states
States.is_state("AL") # True
States.is_state("FL") # True
States.is_state("is_state") # False
States.is_state("__module__") # False
Update
This clearly answer's the OPs question, but readers may also be interested in the Enum
library in Python 3, which would quite possibly be a better container for data such as this.
Why don't you use a dictionary? Its a lot simpler and lookups will be easier as well.
states = {'AL': 'Alabama', 'AK': 'Alaska' ... }
test_state = 'Foo'
if test_state not in states.keys():
print('{} is not valid input'.format(test_state))