r/programminghorror • • 29d ago

Python I love Python

303 Upvotes

81 comments sorted by

View all comments

1

u/jmooroof2 29d ago

I can't imagine a compelling use for this feature. it really should just error

4

u/NFriik 29d ago

There are some use cases for this behavior, but it's reeeaaally limited and you have to know exactly what you're doing. For example, you could use it to cache relatively expensive function calls as default values:

import re
def parse(text, pattern=re.compile(r"\d+")):
  return pattern.findall(text)

This way, instead of re-compilingthe regex every time the function is called, you can just reuse it.

6

u/simonsmine 29d ago

Its not really a feature more a consequence of pythons reference handling. You can do fun things with it though, memosation comes to mind.

1

u/Double_Cost4865 29d ago

It has it’s uses, I just wouldn’t provide default argument like that since it’s wrong. But it’s quite common to modify a list in place and have the changes persist outside the function scope

1

u/4xe1 29d ago

default function parameters are useful, shared function default parameters are efficient, and mutable function parameter are convenient (saves the interpreter the check for mutability, and and saves the user the boiler plate to copy it in a local variable).

What you're seeing is merely a combination of the three.

But shared mutable function parameter is also uniquely useful for memoisation. It's not where you'd put the table of previous results in an other language, but it makes perfect sense to do so in python, as it hides a side effect which is not a real side effect.