简体   繁体   中英

-Python- Can I share functions from 2 scripts?

I have 2 scripts and both need to use a function which is defined on the other script. I want to do something like this:

file1.py:

from file2 import function2
def function1():
    someCode...

... some code where I use function2...

file2.py:

from file1 import function1
def function2():
    someCode...

... some code where I use funcion1 ...

The problem is that it doesn't work and i don't know neither why nor how to fix it. How can I do it?

Option #1 move function1 and function2 to a common file:

common.py :

def function1():
    # some stuff
    pass

def function2():
    # some stuff
    pass

And import function1 and function2 from common.

Option #2 use a local import instead:

def function1():
    someCode...

def some_method_where_function_2_is_used():
    from .file2 import function2
    ... some code where I use function2...

The problem is that the code to run the function from the other file runs on import, so you end up with an endless cycle, which python doesn't like.

To fix, perhaps run the functions in two more separate .py s and define them in another two.

Create an empty __init__.py file in the directory where your files are. This will initialise it as a package and allow you to import the files inside.

Separate 'general' functions into a 'general' module to bypass side-effects.

file1.py:

from utils import function1

file2.py:

from utils import function2

utils.py:

def function1():
    pass

def function2():
    pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM