Hacker News new | ask | show | jobs
by VWWHFSfQ 1068 days ago
> Python arguments are evaluated when the function definition is encountered. Good to remember that!

I would never try to exploit this behavior to achieve some kind of benefit (avoiding max recursion). Any tricks you try to do with this is almost definitely going to to cause bugs that are very difficult to track down. So don't be too clever here.

2 comments

Yeah. I was really surprised to see this as a feature to be used rather than a gotcha. I've seen it more as gotchas, as in actual bugs introduced because of this behavior, and never as a feature until now. I can see why he thinks it's useful though and, maybe within his specific context, it is. That said, even for his example, I think he would have been better off using https://docs.python.org/3/library/functools.html#functools.c...
You are right about that, perhaps it is good to mention it as "gotcha". Or I could have used a better title. I do think though, it is good practice to know this stuff. About the cache decorator: I did link to another article where I discuss lru_cache and cache :)
Before I saw your comment, I had "overlooked" that these were presented as beneficial features, rather than just curiosities. As someone just learning Python, but familiar with other languages, I can only hope that if I start using Python in production with other developers they take the most obvious route (or use a comment as to why they would be relying on this type of behavior).

I chose to learn Python because it seemed to be the easiest to read, which to my mind meant working in a team would lead to easier discovery and understanding. Then I see articles like this, and wonder if I'll have a lot of footguns to watch out for where the code isn't as clear as it seems.

I fully agree on this! Like the Zen of Python says: explicit is better than implicit. You should not expect your teammates know all "special" behavior of the language and if you can write it more straightforward, you should in that case. Guess Kyle mentiones the same about JavaScript in his books. You are right about that. Perhaps that should be a nice addition to the post. I do believe though, it is good to be familiar with this behavior in case you ever come accross such situation.