
If I ran into this (never have), my first inclination would be to write a decorator. The decorator would capture the relevant arguments (either just all of them, or perhaps using the argument names supplied to the decorator when it is called, or perhaps using a custom type hint applied to the method signature letting it know which args to modify) and update their values with the state of the object members in the desired manner. Would look something like: @object_state_args('a') def func(self, a): # value of a has already been updated to self.a, if needed a+=1 return a The opinions regarding the details of what this decorator ought to do would probably vary by use case and by individual preference and I doubt it would be very profitable to add to the std lib, personally. Seems like the type of thing better put in your own toolkit. On Wed, Dec 16, 2020, 8:12 AM Local-State <ain-soph@live.com> wrote:
Hello guys, First time for me to submit a feature request for python.
A lot of time we try to use a member variable as the default value of a member function argument. So we write the code like this: ```python class A: def __init__(self, a: int = 3): self.a = a
def func(self, a: int = None): if a is None: a = self.a a += 1 return a ``` This seems okay, but when there are more than 10 arguments need to set their default values as correlated member variables (with the same name at most times), it'll be very painful and the codes turn out to be quite ugly. I wish a clean coding style, so I write something like this ```python def func(self, a: int = 'self'): for k, v in process(a=a, b=b): eval(f'{k} = v') a += 1 return a
def process(self, **kwargs): return {k: getattr(self, k) if (v == 'self' and k in self.__dict__.keys()) else v for k, v in kwargs.items()} ``` That seems absolutely much worse for sure!
I dream I can just write ```python def func(self, a: int = 'self'): a += 1 return a ``` where I know the default value cannot be 'self', but a special flag which won't get conflict with any other valid argument values. I don't know what it should be though.
Some related questions: python:
https://stackoverflow.com/questions/39928345/python-member-variable-as-param... C++:
https://stackoverflow.com/questions/32399730/default-arguments-as-non-static...
Let me know your ideas!
Ren Pang _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/CTLUXD... Code of Conduct: http://python.org/psf/codeofconduct/