2

I am trying to serialize a Python object into JSON using namedtuple. But I get this error. Google does not help.

Traceback (most recent call last):
 File "cpu2.py", line 28, in <module>
 cpuInfo = collections.namedtuple('cpuStats',('cpu.usr', ('str(currentTime) + " " 
 +str(cpuStats[0]) + " host="+ thisClient')), ('cpu.nice', ('str(currentTime) + " " 
 +str(cpuStats[1]) + " host="+ thisClient')), ('cpu.sys',('str(currentTime) + " " 
 +str(cpuStats[2]) + " host="+ thisClient')), ('cpu.idle',('str(currentTime) + " " 
 +str(cpuStats[3]) + " host="+ thisClient')))
 TypeError: namedtuple() takes at most 4 arguments (5 given)
askance
  • 1,077
  • 4
  • 14
  • 19
  • 3
    The problem is exactly what the error message says. In your call to `namedtuple`, you are passing 5 arguments when it needs only 4. – nickie Sep 09 '13 at 21:30
  • 2
    `namedtuple()` is a function that returns a _type_. After creating one, you can then create instances of that type with data assigned to each of the field names specified when it was created. It looks like you're trying to both create the type and instantiate of it in one statement. Note the examples in the [documentation](http://docs.python.org/2/library/collections.html#collections.namedtuple) on them. – martineau Sep 09 '13 at 22:12

1 Answers1

5

Here is a link to the documentation for namedtuple. You aren't initializing it properly.

How I'm guessing you should initialize it:

cpuInfo = collections.namedtuple('cpuStats', ['usr', 'nice', 'sys', 'idle'])

# In this case, usr=str(currentTime) + " " +str(cpuStats[0]) + " host=" + thisClient
# You can figure the rest out...
info = cpuInfo(usr='fill',
               nice='this',
               sys='your',
               idle='self')

Also, you might want to read this question which talks about serializing namedtuples in json.

Community
  • 1
  • 1
mr2ert
  • 5,146
  • 1
  • 21
  • 32
  • Thanks for the tip - being new to it all, I keep forgetting basic things - initializing and then using, for instance. – askance Sep 09 '13 at 22:53