I saw two other questions like this but they didn't work...
So my question is, I have a function, and I'm making another one in which I need to call the first function. I don't have experience in Python, but I know that in languages like Matlab is possible as long as they're in the same directory.
A basic example:
def square(x):
square = x * x
(and saved)
now in my new function I want to use the function square i tried:
def something (y, z)
import square
something = square(y) + square(z)
return something
which displays: builtins.TypeError: 'module' object is not callable
What should I do?
No need for
import
if its in the same file.Just call
square
from thesomething
function.More simply:
2 way to use a function within an other:
square()
function in another.py
file (ex: myfile.py
) and then, you can import the function this way:import
and you can usesquare()
directly.If, and only if, you have the
square
function defined in asquare
module, then you should look to import the simple name from it instead.If you don't want to change anything, then you need to use its fully qualified name:
The module's name is
square
, and you can't call functions on modules.You have several options.
Put everything in one file. Then you only need to call the other function; forget about all
import
s then.Put the
square
function in a different file, e. g.foo.py
. Then your using function needs toimport
it. For that you have two options again:import foo
and usefoo.square(y)
orfrom foo import square
and usesquare(y)
. (You can name your module like your function as well -- the two have separate name spaces -- so then you would have tofrom square import square
.)Modules (i. e. in a separate file) are used for grouping logically connected things together, e. g. all mathematical functions, all operating-system related things, all random number generator related things, etc. So in your case which looks like a first test I'd propose to put everything in one file and forget about all
import
s.