Note that there are some explanatory texts on larger screens.

plurals
  1. POPython3 — replacing a dynamically chosen namedtuple field
    primarykey
    data
    text
    <p>I am modeling database records using <code>collections.namedtuple</code>. At times, I want the user to be able to replace the contents of an arbitrary field. The <code>_replace()</code> method permits replacing the contents of a specific field as long as we can specify its name as part of the argument: <code>somenamedtuple._replace(somefield=newcontent)</code>. But if the name itself is to be dynamically supplied by the user, I am unable to find a way to do it.</p> <p>Here is a minimal working example:</p> <pre><code>from collections import namedtuple fields = ['one', 'two', 'three'] Record = namedtuple('Record', fields) # Populate fields. record = Record(*tuple(['empty' for i in fields])) while True: # Show what we have already. print('0: quit') for i in range(len(fields)): print('{}: {}: {}'.format(i+1, fields[i], record[i])) to_change = int(input('Field to change: ')) if not to_change: break else: new_content = input('New content: ') field_to_change = {fields[to_change-1]:new_content} print('Setting', field_to_change) record._replace(**field_to_change) print('Finished.') print(record) </code></pre> <p>Output (Ipython 1.0.0, Python 3.3.1) follows. </p> <pre><code>In [1]: run test_setattr_namedtuple 0: quit 1: one: empty 2: two: empty 3: three: empty Field to set: 2 New content: asdf Setting {'two': 'asdf'} 0: quit 1: one: empty 2: two: empty 3: three: empty Field to set: 0 Finished. Record(one='empty', two='empty', three='empty') In [2]: </code></pre> <p>The <code>record._replace()</code> line is attempting to set 'two' to 'asdf', rather than <code>two</code> and so fails silently. I had thought of using <code>eval</code> inside <code>_replace()</code>, but <code>_replace()</code> does not accept expressions as arguments.</p> <p>I also tried the built-in function <code>setattr</code>, but it doesn't work with namedtuples, presumably because they are immutable. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload