Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call a function from another file?

Tags:

python

Sorry basic question I'm sure but I can't seem to figure this out.

Say I have this program , the file is called pythonFunction.py:

def function():
   return 'hello world'

if __name__=='__main__':
   print function()

How can I call it in another program? I tried:

import pythonFunction as pythonFunction
print pythonFunction.function

Instead of 'hello world', I get ...I have done this in the past by making the first file a class, but I was wondering how to import the function correctly? If it helps, in my real file, I am printing a dictionary

like image 709
Lostsoul Avatar asked Oct 09 '11 05:10

Lostsoul


People also ask

How do you call a function from another file?

To use the functions written in one file inside another file include the import line, from filename import function_name . Note that although the file name must contain a . py extension, . py is not used as part of the filename during import.

How do you call a function from another file in Colab?

If you expand the files tab in Colab you can navigate to the files in Google Drive. Then you can right click on the file or folder you want and do Copy path . You can then paste this into the cell where path_to_module is defined.


1 Answers

You need to print the result of calling the function, rather than the function itself:

print pythonFunction.function()

Additionally, rather than import pythonFunction as pythonFunction, you can omit the as clause:

import pythonFunction

If it's more convenient, you can also use from...import:

from pythonFunction import function
print function() # no need for pythonFunction.
like image 82
icktoofay Avatar answered Oct 10 '22 10:10

icktoofay