Mutable default argument for a Python namedtuple

2024/10/7 4:23:03

I came across a neat way of having namedtuples use default arguments from here.

from collections import namedtuple
Node = namedtuple('Node', 'val left right')
Node.__new__.__defaults__ = (None, None, None)
Node()

Node(val=None, left=None, right=None)

What would you do if you would want the default value for 'right' to be a empty list? As you may know, using a mutable default argument such as a list is a no no.

Is there a simple way to implement this?

Answer

You can't do that that way, because the values in __defaults__ are the actual default values. That is, if you wrote a function that did had someargument=None, and then checked inside the function body with someargument = [] if someargument is None else someargument or the like, the corresponding __defaults__ entry would still be None. In other words, you can do that with a function because in a function you can write code to do whatever you want, but you can't write custom code inside a namedtuple.

But if you want default values, just make a function that has that logic and then creates the right namedtuple:

def makeNode(val=None, left=None, right=None):if right is None:val = []return Node(val, left, right)
https://en.xdnf.cn/q/70284.html

Related Q&A

Windows notification with button using python

I need to make a program that alerts me with a windows notification, and I found out that this can be simply done with the following code. I dont care what library I use from win10toast import ToastNo…

numpy IndexError: too many indices for array when indexing matrix with another

I have a matrix a which I create like this:>>> a = np.matrix("1 2 3; 4 5 6; 7 8 9; 10 11 12")I have a matrix labels which I create like this:>>> labels = np.matrix("1;0…

how to use enum in swig with python?

I have a enum declaration as follows:typedef enum mail_ {Out = 0,Int = 1,Spam = 2 } mail;Function:mail status; int fill_mail_data(int i, &status);In the function above, status gets filled up and wi…

What does except Exception as e mean in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 4…

Numpy efficient big matrix multiplication

To store big matrix on disk I use numpy.memmap.Here is a sample code to test big matrix multiplication:import numpy as np import timerows= 10000 # it can be large for example 1kk cols= 1000#create some…

Basic parallel python program freezes on Windows

This is the basic Python example from https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool on parallel processingfrom multiprocessing import Pooldef f(x):return x*xif __na…

Formatting multiple worksheets using xlsxwriter

How to copy the same formatting to different sheets of the same Excel file using the xlsxwriter library in Python?The code I tried is: import xlsxwriterimport pandas as pd import numpy as npfrom xlsxw…

Good python library for generating audio files? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Keras ConvLSTM2D: ValueError on output layer

I am trying to train a 2D convolutional LSTM to make categorical predictions based on video data. However, my output layer seems to be running into a problem:"ValueError: Error when checking targe…

debugging argpars in python

May I know what is the best practice to debug an argpars function.Say I have a py file test_file.py with the following lines# Script start import argparse import os parser = argparse.ArgumentParser() p…