Rename named parameter in Python to avoid naming conflicts with import statement

  • A+
Category:Languages

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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: