1

I was referring to this question to call a Python function from another Python file.

So I have 2 Python scripts in the same folder: myFunc.py and caller.py.

First, I defined a simple function in myFunc.py as following:

def mySqrt(x):
    return x**2

...then I tried to use this function in my caller.py, like this:

import myFunc as mySqrt

a = mySqrt(2)
print(a)

...but it returns:

'module' object is not callable

...when the script caller.py is executed.

What did I do wrong here?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Nick X Tsui
  • 2,737
  • 6
  • 39
  • 73

4 Answers4

2

What you have:

import myFunc as mySqrt

imports the module and gives it a different name.

You want:

from myFunc import mySqrt
Community
  • 1
  • 1
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
2

As the question you mentioned states use:

from myFunc import mySqrt

as is used to create alias to the module, so you could shorten the typing, like in the following example:

from myFunc import mySqrt as ms
a = ms(2)
print(a)
#4
zipa
  • 27,316
  • 6
  • 40
  • 58
2

Here's what you should have:

from myFunc import mySqrt

Explanation:

  • import <module> as <module_alias>

This instruction imports <module> under the name <module_alias>.

So import myFunc as mySqrt would import the module myFunc under the name mySqrt, which is not what you want!

  • from <module> import <function>

This instruction imports <function> from <module>.

So from myFunc import mySqrt would import the function mySqrt() from your module myFunc, which is the behavior you're looking for.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
2

You are giving an alias to your import that has the same name as the function you want to call. Try:

from myFunc import mySqrt

Or if you want to keep the same formatting, try:

import myFunc as mf

a = mf.mySqrt(2)
print(a)
kingJulian
  • 5,601
  • 5
  • 17
  • 30