Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python -- using function attributes as return values [duplicate]

Tags:

python

enums

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?

like image 811
RexE Avatar asked Oct 03 '22 13:10

RexE


2 Answers

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>
like image 88
Ethan Furman Avatar answered Oct 12 '22 12:10

Ethan Furman


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
like image 31
arshajii Avatar answered Oct 12 '22 12:10

arshajii