It certainly is possible, and is frequently a good idea. This is for exactly the reason you cite: if you have all your code in one big file, it gets annoying to edit that one file.
So, for example, let's say you have a calculator function and some class. You can put them in two separate files -- the first in calc.py
# calc.py
def calculator(a,b):
return a.do_something_clever(b)
and the second in some other file
# cleverness.py
class Cleverness(object):
def do_something_clever(self, c):
return 3.14159+c
To use them from some other script, you just need to import them:
# cool_script.py
from calc import calculator
from cleverness import Cleverness
c = Cleverness()
print(calculator(c, 2.717))
Instead of from x import y
, you can also use import x
and then x.y
. For example, the following is equivalent:
# cool_script2.py
import calc
import cleverness
c = cleverness.Cleverness()
print(calc.calculator(c, 2.717))
There's always a balancing act between making too many separate files and making too few. Basically, it's up to you. The main factor that drives my decision is usually how closely related the different things are, and how reusable the different components would be if they were separated. For example, if my calculator
function did something complicated, but didn't depend at all on the details of Cleverness
, I would make sure to put it in a separate file. On the other hand, if I always import Cleverness
whenever I import calculator
, and the codes for both were simple, I'd probably just stick them into the same file. And if I'm never going to use the code in them again, I'd probably just stick them in the main script's file itself.