Set an optional variable in the named tuple

from collections import namedtuple

FooT = namedtuple('Foo', 'foo bar')
def Foo(foo=None, bar=None):
  return FooT(foo,bar)

foo = Foo()
foo.foo = 29
throws attribute error

So my use case is a data structure that has optional fields. but should be able to change it if necessary.

+4
source share
5 answers

A defaultdictshould match what you want. It works by providing it with a build function that it calls every time access to the unset element. Here is a demo:

>>> from collections import defaultdict
>>> d = defaultdict(lambda:None)
>>> d['foo'] = 10
>>> d['bar'] = 5
>>> print d['baz']
None
>>> d['baz'] = 15
>>> print d['baz']
15
+5
source

Tuples are, by definition, immutable. Named vertices follow this pattern.

In python3, it appears that you can use SimpleNamespace [1]. If you want to just use the read / write data structure, although you can create a class and set restrictions on its members.

[1] - Python , .. namedtuple

+3

, , . namedtuple, ok ( ) _replace, , .

from collections import namedtuple

FooT = namedtuple('Foo', 'foo bar')
def Foo(foo=None, bar=None):
  return FooT(foo,bar)

foo = Foo()
foo = foo._replace(foo=29)
+2

, tutorial , None undefined ? :

class Foo(object):
    def __getattr__(self, name):
        return None

, defaultdict, , .

+1

?

class Foo(object):

   def __init__(foo=None, bar=None):
     self.foo = foo
     self.bar = bar

foo = Foo()
foo.foo = 29
0

Source: https://habr.com/ru/post/1598444/


All Articles