I have a function that has a few possible return values. As a trivial example, let's imagine it took in a positive int and returned "small", "medium", or "large":
def size(x):
if x < 10:
return SMALL
if x < 20:
return MEDIUM
return LARGE
I am wondering the best way to write & define the return values. I am wondering about using Python function attributes, as follows:
def size(x):
if x < 10:
return size.small
if x < 20:
return size.medium
return size.large
size.small = 1
size.medium = 2
size.large = 3
Then my calling code would look like:
if size(n) == size.small:
...
This seems like a nice built-in "enum", possibly clearer/simpler than creating a module-level enum, or defining the 3 values as global constants like SIZE_SMALL, SIZE_MEDIUM
, etc. But I don't think I've seen code like this before. Is this a good approach or are there pitfalls/drawbacks?
While you can, I wouldn't, especially now that Python has an Enum type in 3.4 which has been backported.
Your example above might look like this as an Enum
:
class Size(Enum):
small = 1
medium = 2
large = 3
@classmethod
def classify(cls, number):
if number < 10:
return cls.small
elif number < 20:
return cls.medium
else:
return cls.large
In use:
--> Size.classify(15)
<Size.medium: 2>
namedtuple
, perhaps?
>>> from collections import namedtuple
>>>
>>> SizeSpec = namedtuple('SizeSpec', ['small', 'medium', 'large'])
>>>
>>> size = SizeSpec(small=1, medium=2, large=3)
>>>
>>> size.small
1
>>> size.medium
2
>>> size.large
3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With