Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate namedtuple values?

I had namedtuple variable which represents version of application (its number and type). But i want and some restriction to values:

Version = namedtuple("Version", ["app_type", "number"])
version = Version("desktop") # i want only "desktop" and "web" are valid app types
version = Version("deskpop") # i want to protect from such mistakes

My solution for now is primitive class with no methods:

class Version:
    def __init__(self, app_type, number):
        assert app_type in ('desktop', 'web')

        self.app_type = app_type
        self.number = number

Is it pythonic? Is it overkill?

like image 419
keran Avatar asked Jun 26 '19 19:06

keran


People also ask

How do I get values from Namedtuple?

From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.

Can Namedtuple be pickled?

@Antimony: pickle handles namedtuple classes just fine; classes defined in a function local namespace not so much.

What is difference between Namedtuple and tuple?

Tuples are immutable, whether named or not. namedtuple only makes the access more convenient, by using names instead of indices. You can only use valid identifiers for namedtuple , it doesn't perform any hashing — it generates a new type instead.

When can you change the value of a Namedtuple?

Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field.


1 Answers

You could use enum.Enum, and typing.NamedTuple instead of collections.namedtuple:

Maybe something like this:

from typing import NamedTuple
import enum

class AppType(enum.Enum):
    desktop = 0
    web = 1

class Version(NamedTuple):
    app: AppType


v0 = Version(app=AppType.desktop)
v1 = Version(app=AppType.web)

print(v0, v1)

output:

Version(app=<AppType.desktop: 0>) Version(app=<AppType.web: 1>)

A undefined AppType raises an AttributeError:

v2 = Version(app=AppType.deskpoop)

output:

AttributeError: deskpoop
like image 66
Reblochon Masque Avatar answered Oct 16 '22 03:10

Reblochon Masque