osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Accessing parent objects


On Sunday, March 25, 2018 at 10:02:20 AM UTC-5, Jugurtha Hadjar wrote:
[...]
> Furthermore, the only case I'd use a positional argument is
> if I were 100% certain the code will not change, which I'm
> not.

And short of you possessing a crystal ball in good working
order (mine's currently in the shop!), you must always
assume that code will grow over time, and thus, write your
code in a manner that is as easy to extend and maintain as
possible.

> Plus when the API will change (and it will), it will be
> harder to deal with it that if it were a keyword argument.

Huh? Was that a typo? Did you mean "_not_ a kwarg"???

> If you change the order you'd have to change the whole
> codebase where the class/function is instantiated/called,

If the args are positional, then yes.

> whereas if you use a keyword argument, you could just catch
> the old way call, issue a deprecation warning, then route
> the call for the new way call.

Whew! It _was_ a typo. ':-)

> [...]
>
> Suppose I have a class like this:
>
> class Foo(object):
>      def __init__(self, name, height, address):
>          self.name = name
>          self.height = height
>          self.address = address
>
> Suppose I then want to change it to:
>
> class Foo(object):
>      def __init__(self, status, name, address, height):
>          self.status = status
>          self.name = name
>          self.height = height
>          self.address = address
>
>
> This would totally screw up other parts of the code where
> the class is used. I tend to use positional arguments when
> it's *way* unlikely the code will ever change, and even
> then I probably wouldn't.

Positional arguments are not without their practical
advantages though. For instance: you don't have to manually
unpack the arguments into local vars, plus, you can let
Python handle the underflow/overflow of arguments. Of
course, the con is that positional arguments do not scale
nicely; which leads to nasty backwards incompatible issues.

It's a tough call, really. Because as programmers we are
inclined to be naturally lazy (it's a virtue!), and thus,
we'd prefer to offload as much work as we can on the
processor. But if saving a few keystrokes now means hours of
painful search&replace sessions later, hmm, probably best to
choose the path with the best long-term outcome.