1

I'm writing a class definition with several methods. The __init__ method instantiates a list as an argument, and I'd like one of the methods to take a keyword argument with a default value that matches the list in length. Consider the code snippet:

class widget(object):
     def __init__(self, *attr_list):
         self.attr_list = attr_list
     def fancy_method(self, arglist = (None,) * len(self.attr_list)):
         pass

I suppose I can just run the code and try instantiating a widget, but can anyone provide enlightening commentary on the order of operations and acceptable variable references? Perhaps propose an alternative syntax that's easier to agree with?

EDIT: A similar question was asked and answered here How can I make the default value of an argument depend on another argument (in Python)? but I'm curious to know how the interpreter treats the matter when the parameter, namely attr_list, isn't an argument in the same function as the keyword argument it parameterizes. Is fancy_method and its behavior defined upon the widget definition? Or can the default argument be defined upon instantiation instead? The other question doesn't include this ambiguity because the default argument would have to be defined upon the function's call, not its definition.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
user2569332
  • 555
  • 1
  • 4
  • 12
  • Why do you want a mutable default value? – Ignacio Vazquez-Abrams May 08 '18 at 02:14
  • 2
    See here: https://stackoverflow.com/questions/21804615/how-can-i-make-the-default-value-of-an-argument-depend-on-another-argument-in-p – cs95 May 08 '18 at 02:19
  • @IgnacioVazquez-Abrams, I don't need it to be mutable. I've edited the question to suggest it could be a tuple as well. Really what I need is the length to match that of self.attr_list. – user2569332 May 08 '18 at 03:10

0 Answers0