Accessing parent objects
Ian Kelly
ian.g.kelly at gmail.com
Sun Mar 25 11:16:19 EDT 2018
On Sun, Mar 25, 2018 at 9:01 AM, Jugurtha Hadjar
<jugurtha.hadjar at gmail.com> wrote:
>
> On 03/25/2018 03:25 PM, Terry Reedy wrote:
>>
>> On 3/25/2018 7:42 AM, Jugurtha Hadjar wrote:
>>
>>> class C2(object):
>>> def __init__(self, parent=None):
>>> self.parent = parent
>>
>>
>> Since parent is required, it should not be optional.
>>
>
> You can still call it the way you'd call it if it were a positional
> argument.
>
> i.e:
>
> def foo(keyword_argument=None):
> print(keyword_argument)
>
> foo(3)
> foo(keyword_argument=3)
>
>
> Just because it's a keyword argument doesn't mean it's not required. I could
> have provided a default using `self.parent = parent or C2`, but I didn't
> want to assume C2 was defined in that namespace and wanted to give as
> generic a code as I could.
You misunderstand what keyword arguments are. Giving the argument a
default does not make it a keyword argument. Passing the argument with
keyword syntax is what makes it a keyword argument. It happens at the
call site, not when it's defined (with the exception of keyword-only
arguments, which this is not).
This function takes an argument x either by position or by keyword:
def foo(x): pass
This function also takes an argument x either by position or by keyword:
def foo(x=None): pass
The only difference is that the latter makes the argument optional by
assigning a default, whereas the former requires it.
The point is, if the argument is effectively required and doesn't have
a sensible default, then don't make it optional. You can still pass it
by keyword if that's what you want.
More information about the Python-list
mailing list