Question

I am quite new to Python and I don't know what is available. Currently, I have this piece of code to quickly put some named variables together, so I can use them in other places:

def myfunction():
    props = namedtuple('props', '')

    props.color = "green"
    props.size = "large"
    props.wheels = 4
    props.roof = True

    return props

Is in this case the namedtuple a good solution? Or can it be simpler?

Was it helpful?

Solution

namedtuple is excellent tool to produce fixed-sized pieces of (immutable) information, just like tuples but with named attributes for convenience.

However, you are using the namedtuple class factory incorrectly. props is a class, you normally would use it like this:

Props = namedtuple('Props', 'color size wheels roof')

def myfunction():
    props = Props(color="green", size="large", wheels=4, roof=True)
    return props

This makes props immutable (the end-user can generate a new instance by using the namedtuple._replace() method), and indexable as well.

The only reason you didn't run into issues with your approach is that you create a new class object each time your function runs; the class attributes you set on it are not shared between instances because no instances are ever created.

If you didn't want an immutable object, use a dictionary instead:

def myfunction():
    return {
        "color": "green",
        "size": "large",
        "wheels": 4,
        "roof": True
    }

OTHER TIPS

If you're just using props to store data, the simplest option would be to use a dict:

def myfunction():
    return {"color": "green",
            "size": "large",
            "wheels": 4,
            "roof": True}

Elements of the dict are then accessed as props["color"] and so forth (once you've stored the return value in a variable named "props", of course).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top