Is it seen as bad practice to try to hide local functions in Python? The intention not to clutter the global namespace with second rank or common function names may stand against ... er... some Pythonisms that I am not aware of.
def foo(aparameter):
def somenamewhichislikelytoclash(anotherparam):
....
Is there a runtime penalty? AFAIK all functions contexts are created on the heap anyway, so binding and destroying would take just as much time for locals - is there more?
I am asking this for the Python context specifically, as I know enough about separation of concerns, clean keeping of namespace etc. in other languages.
1 Answer 1
Hiding/shadowing like this is generally a bad idea from a code maintenance perspective. Unless the location of definition is very near its use (so a programmer can keep both definition and use in the same visual context) then it's too easy to get confused. Even then, re-factoring and other code maintenance could wash the definition downstream and then definition and use may not be near one another.
There are very few scenarios where you need/want to reuse a function name unless you are overriding previously defined functionality and, in that case, you should probably be introducing some object/class structure to accommodate this behavior.
-
I see your points. The motivation to ask came from a very different scenario, though - I was writing some combinatorial functions which become so much more tidied up if you introduce small helper functions, e.g. stepping an array of indices from 0 to maximum in a very specific way. I can't come up with any more clever names than
stepix
or the like, and if you have a number of algorithms then there are more functions which need to step an index - but I think my question is sufficiently answered. Thanks.Vroomfondel– Vroomfondel2017年12月07日 20:35:51 +00:00Commented Dec 7, 2017 at 20:35 -
I think a scenario where you are reusing small helper functions that are pretty specific to that scope your working in, its a pretty reasonable use case for name hiding. Jim brings up a good point about how it could be problematic for maintenance/ readability, but I think in your use case its a good fit and could improve readability.Zv_oDD– Zv_oDD2019年01月25日 19:30:54 +00:00Commented Jan 25, 2019 at 19:30
somenamewhichislikelytoclash
function is only used withinfoo
, and is indeed likely to clash its name with some other function within the same module, a closure makes perfect sense.from module import *
), but this is a bad practice in itself, so let's ignore that.stepix
etc. where no two stepping functions tend to be identical.