[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1293
  • Last Modified:

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.
0
Evan Cutler
Asked:
Evan Cutler
  • 2
  • 2
2 Solutions
 
peprCommented:
Just put the definitions of the functions into the separate file with the .py extension, and (for simplicity) place that file in the same directory as your main script file:

myutils.py
def fn():
    print('fn called')

Open in new window


Your script imports the module (use the file name without extension).
script.py
import myutils

myutils.fn()

Open in new window

And that is all. The module name must be used as the part of the name of the function inside. Or you can import the specific function from the module and use it without the module name:
from myutils import fn

fn()

Open in new window

0
 
Evan CutlerAuthor Commented:
awesome.  If the import(?) is not in the same folder as the main.py file....do I import folder/name?
THanks
0
 
peprCommented:
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.
0
 
Nas-BanovCommented:
As additional note, you can import all functions/entities from that file with
from myutils import *

Open in new window

0
 
Evan CutlerAuthor Commented:
Thank you so much guys.
I have alot more questions, but that requires more points. ;)

Thanks again.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now