Say I have a function foo
in a big Python project that has a named argument bar
:
def foo(bar=42):
do_something_with_bar(bar)
This function is called a lot in the codebase, in calls that use or omit the named bar
parameter.
Now say I'm changing this function because it has a bug and want start using a function from a certain package, that is coincidentally also called bar
. I cannot use the bar
function when I import it like this:
from package import bar
def foo(bar=42):
# how can I use the package.bar function here?
do_something_with_bar(bar)
I could use something like:
from package import bar as package_bar
But this file also contains a lot of invocations of bar
so that's a no-go.
The only way I can see this working is to rename the bar
method from package
:
from package import bar
package_bar = bar
def foo(bar=42):
do_something_with_bar(package_bar(bar))
Or to import it multiple times (untested):
from package import bar, bar as package_bar
def foo(bar=42):
do_something_with_bar(package_bar(bar))
Is there some way I can rename the bar
parameter in the foo
function, without all calls to the foo
function breaking in the entire codebase?
This is a common issue. In this case, it helps to have an additional import statement for package
, so you can safely refer to package
's bar
through the package
namespace without running into naming conflicts.
import package
from package import bar
def foo(bar=42):
do_something_with_bar(package.bar(bar))
You still end up importing the module once, but you now have two ways of referring to bar
.
Replace the function body with a call to another function with differently named arguments:
from package import bar
def foo(bar=42):
return _foo(baz=bar)
def _foo(baz):
do_something_with_bar(bar(baz))
Then you are free to use bar
in that function as the name of the function from the package rather than the argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With