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
  • 8,910
  • 6
  • 33
  • 52
Nick X Tsui
  • 2,536
  • 6
  • 35
  • 66

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
  • 44,696
  • 30
  • 102
  • 125
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
  • 26,044
  • 6
  • 38
  • 55
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
  • 8,910
  • 6
  • 33
  • 52
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
  • 4,704
  • 3
  • 18
  • 29