Is it possible to declare functions in python and define them later or in a separate file?
I have some code like:
class tata:
def method1(self):
def func1():
# This local function will be only used in method1, so there is no use to
# define it outside.
# Some code for func1.
# Some code for method1.
The problem is that the code becomes messy and difficult to read. So I wonder if it's possible for instance to declare func1
inside method1
and define it later?
You can simply “cls” to clear the screen in windows.
Sure, no problem:
foo.py:
def func1():
pass
script.py:
import foo
class tata:
def method1(self):
func1=foo.func1
I think what you want is to import the function within method1
, e.g.
def method1(...):
from module_where_func1_is_defined import func1
# do stuff
something = func1(stuff, more_stuff)
# do more stuff
Python modules are basically just files; as long as the file module_where_func1_is_defined.py
is in the same directory as your script, method1
will be able to import it.
If you want to be able to customize the way method1
works, and also make it even more clear that it uses func1
, you can pass func1
to method1
as a default parameter:
import other_module
# various codes
def method1(other_args, func=other_module.func1)
# do stuff
something = func(stuff, more_stuff)
# do more stuff
If func1() needs to handle anything contained in the scope of method1() you're best leaving func1()'s definition there. You'll have to have func1() receive any pertinent data as parameters if it's not defined within the scope of method1()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With