0

The following function demonstrates a coworker's coding style:

def one_week_after(date=datetime.date(2011,3,8)):
    return date+datetime.timedelta(days=7)

Every argument of every function they write has a default value, whether there's a natural default or not.

Is there something like PEP 8 that I can use to explain why this is considered a bad practice? (And certainly not pythonic)

TylerH
  • 20,799
  • 66
  • 75
  • 101
user357269
  • 1,835
  • 14
  • 40
  • i don't think having default arguments is bad, it saves you the time of passing arguments when calling the function – Daniel Afriyie Aug 31 '22 at 21:07
  • 1
    Where did they get the idea that that's *good*? – Kelly Bundy Aug 31 '22 at 21:07
  • 3
    I'm not aware of any specific standard that explicitly states something like this is bad practice, but let's be realistic here. What exactly is the point of injecting arbitrary data into a function? Imagine you forgot to pass a parameter, but the function executes anyways and returns valid data, yet incorrect data. This alone should be reason enough. – iced Aug 31 '22 at 21:07
  • 1
    Meaningful default values are fine, but always adding them circumvents the `TypeError` that should be raised and that you want to be raised when a function is not called with the expected signature. This is similar to writing something like `try ... expect Exception: pass` and you can read [here](https://stackoverflow.com/questions/21553327/why-is-except-pass-a-bad-programming-practice) why this is considered bad practice. – Alperino Aug 31 '22 at 21:33
  • @DanielAfriyie The question is specifically about cases where there is no natural or sensible default, yet the coworker picked one anyway. Imagine if Python's `next` function had some random iterator somewhere as a default argument. Or if it had *any* default argument, for that matter. – CrazyChucky Sep 01 '22 at 00:48

1 Answers1

1

Maybe line 2 of the Zen of Python (PEP 20)

Explicit is better than implicit.

Calling the function as one_week_after() passes the default argument implicitly in a way that isn't obvious to the reader.

user357269
  • 1,835
  • 14
  • 40