Home > database >  Writing common Functions in a separate File in Python
Writing common Functions in a separate File in Python

Time:10-17

I have few functions in Python that are used across 8 different applications. So, I'd like to create a common functions file with a separate class and use it in several application.

What is the best approach. Below is my sample code.

common_func.py

import time

class common_funcs(object):
    
    def func1(func):
        def ret_func(*args, **kwargs):
            statement (....)
            while True:
            odc = ****
            if odc == 100:
                statement (....)
                continue
            break
        return rsp
    return ret_func

    @func1
    def nda_cal(ar1, ar2):
        res = xxxx(ar1, ar2)
        return res
    
    def func3():
        statement 1.... 
        return xyz
    
    def func4():
        return abc

Now I'd like to import func4 of this class in the file common_func.py into other application's code. How can I do it efficiently?

Thank you in advance.

CodePudding user response:

Generally speaking, you could import the common_func.py code into another python file like below:

from common_func import common_funcs # First, import your python file
obj = common_funcs() # Then, instantiate the class containing func4
func4_Results = obj.func4()# Finally, call func4

Note that you may have to revise the import statement to match where your common_func.py file is located.

To your question - without having more information about your situation, its difficult to say which method of importing a python file would be the "most efficient".

However, the link below points to another thread which offers a few different ways to import a python file, which may help you in determining which method is the best for your situation:

Stackoverflow - How do I import other Python files?

  • Related