Example code from a module:
somevar = "a"
def myfunc(somevar = None):
# need to access both somevars ???
# ... if somevar was specified print it or use the global value
pass
if __name__ == '__main__':
somevar = "b" # this is just for fun here
myfunc("c")
myfunc() # should print "a" (the value of global variable)
There are at least two reasons for using the same name:educational (to learn how to use local/globals) and usage in modules.
Let say that this code is part of your module: mymodule and you want to do things like:
import mymodule
mymodule.samevar = "default"
...
mymodule.myfunc(somevar = "a")
...
mymodule.myfunc()
As you can imagine in this example is simplified, imagine that somevar parameter is one of many optional parameters and that myfunc is called in many places.
By far the best approach, as the other answers say, is to avoid this very, very bad design: just don’t use the same names for two different things!
If you’re locked into this terrible design, maybe because your company’s Supreme Architect decreed it and it’s just non-negotiable (e.g., there’s tons of customer code relying on the names of both the global and the parameter), the first order of business for you is to make sure your resume is up to date, print it on the best printer, and start getting in touch with members of your social network to look for a job at a place that’s run more sensibly; next, to avoid losing health insurance until a better job is found, try
I’ve also renamed your
mufunctomyfuncbecause that’s the name it’s being called with (though given the incredibly bad design your hypothetical Supreme Architect seems to be able to perpetrate, maybe he’s also specified that the function be called by a different name from the one it’s defined with? seems to go with the systematic name conflict this hypothetical but already pretty hateful guy is assumed to have foisted on you!-).