If I have a function defined in my code lets call foo(), and I use the following code:
from mod1 import *
With mod1 containing a function also with the same name of foo() and call the foo() function, will this override my original definition of the function when it evaluates it?
5 Answers 5
As far as I know it will.
you would need to either rename you foo() function you have built OR change your module input to read
import mod1 and subsequently define any use of the foo() function from mod1 to mod1.foo()
Comments
Depends on where the function is:
def foo():
pass
from mod1 import *
foo() # here foo comes from mod1
# -------
# another interesting case
def foo():
from mod1 import *
foo() # this will also call foo from mod1
foo() # but this one is still the foo defined above.
# ---------
# The opposite
from mod1 import *
def foo():
pass
foo() # here foo is the one defined above
Anyway, from module import * is considered a VERY bad and error-prone practice. It is a kind of using namespace std;-like thing in C++. Avoid it as much as possible.
Comments
a.py
def foo():
print 'Hello A'
Test
>>> def foo():
... print 'Hello 1'
...
>>> foo()
Hello 1
>>> from a import *
>>> foo()
Hello A
>>> def foo():
... print 'Hello 2'
...
>>> foo()
Hello 2
Comments
I get the following:
file mod1.py contains
def foo():
print "hello foo"
and then i start python interpreter and do the following:
>>> def foo():
... print "hello world"
...
>>> from mod1 import *
>>> foo()
hello foo
>>>
So yes, it would override.
Unless you then do, a new
def foo():
print "new foo"
In which case it would print "new foo"
Comments
It depends on the relative order of the function definition and the import statement. Whichever is executed second will override the first.
import *)