2

Attempting to run this code in Python3 Jupyter notebook :

t = namedtuple('a', 'b')
a = [1,0,1]
b = [1,1,1]
Out, In = np.asanyarray(a), np.asanyarray(b)
t(Out.shape[0], *In.shape)

returns error :

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-151-7955ff03a60d> in <module>()
      3 b = [1,1,1]
      4 Out, In = np.asanyarray(a), np.asanyarray(b)
----> 5 t(Out.shape[0], *In.shape)

TypeError: __new__() takes 2 positional arguments but 3 were given

Is possible to create namedtuple with two arguments ?

Update :

Why does this not cause similar issue :

t = namedtuple('ps', 'Out In S')

a = np.asanyarray([[1]])
b  = np.asanyarray([[1]])

d = t(a.shape[0], *b.shape)

d

computes :

ps(Out=1, In=1, S=1)

Update 2 :

Think i understand now namedtuple('ps', 'Out In S') translates to namedtuple('name_of_tuple', 'tuple_values_seperated_by_spaces')

blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • 3
    The first argument of named tuple, is the name of the named tuple, not the arguments. – Willem Van Onsem Nov 21 '17 at 10:47
  • 1
    You are using the `namedtuple` incorrectly. [Check the docs on what the parameters should be](https://docs.python.org/3/library/collections.html#collections.namedtuple). – poke Nov 21 '17 at 10:48

1 Answers1

9

The first argument of named tuple constructor, is the typename: the name of the named tuple, not the arguments. [documentation]

So you should construct t as:

#                   v parameters
t = namedtuple('t', ('a', 'b'))
#              ^ type name

To make it more convenient, you can also provide a space separated string of parameters. So an equivalent one is:

#t = namedtuple('t', 'a b')
#                    ^ space separated list of parameters
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555