how to call a function from another file?

Question:

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

Asked By: Lostsoul

||

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.
Answered By: icktoofay
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.