Link to home
Start Free TrialLog in
Avatar of Evan Cutler
Evan CutlerFlag for United States of America

asked on

how do I use python functions in a separate .py file?

Greetings,
I'm writing a python script for someone as my first attempt in learning python.

The script is getting long, and I want to include functions.
But instead of putting all the functions in the front of the same file, I was wondering if there was a way to put it in a different file and refer to that function from the main .py file.

Thanks much.
ASKER CERTIFIED SOLUTION
Avatar of pepr
pepr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Evan Cutler

ASKER

awesome.  If the import(?) is not in the same folder as the main.py file....do I import folder/name?
THanks
Avatar of pepr
pepr

No. The import is more abstract (see https://docs.python.org/3/reference/simple_stmts.html#the-import-statement for various forms of the statement). Think about it similarly as about searching executables in OS using the PATH variable. Python has some rules where to search for the file of the name. Actually, there is the sys module that implements sys.path as list of directories where the modules are searched (see https://docs.python.org/3/library/sys.html#sys.path).

You can print the sys.path, and you can modify it if you need.

If you need to implement some hierarchy of modules, it is usually done via packages (https://docs.python.org/3/reference/import.html#regular-packages) that differ from a simple directory hierarchy. I suggest to read the doc or simply leave it out for now.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you so much guys.
I have alot more questions, but that requires more points. ;)

Thanks again.