Python renew a function's definition of imported module and use renewed one in even functions of imported module

Question:

I have a file1.py:

def funcCommon1():
    pass
def file1Func1():
    funcCommon1()
    ....#other lines of code

and I have a file2.py which I have imported funcs of file1.py

from file1 import *
def file2FuncToReplacefuncCommon1():
    ....#some lines of code
def funcCommon1():#renewed or lets just say replaced `funcCommon1` definition
    file2FuncToReplacefuncCommon1()

but in file1Func1, funcCommon1() refers to pass defenition but I want to refer to file2FuncToReplacefuncCommon1.
I know in file1.pyI cant do from file2 import * because it will go to infinite loop. or I dont want to pass funcCommon1 as an argument to funcs like file1Func1. something like:

def file1Func1(funcCommon1):
    funcCommon1()
    ....#other lines of code

so is there any other way I can renew the definition of funcCommon1 in file1Func1.

Asked By: Farhang Amaji

||

Answers:

This is fundamentally not how Python works. What you call "renew" is simply defining a new function in a completely different namespace.

What you should do is pass the function as an argument. This is sane, normal way to approach this.

But if you want something close to what you are doing, you can do this (totally not good thing) instead:

in file2.py:

import file1 # You shouldn't have been using starred imports to begin with

def file2FuncToReplacefuncCommon1():
    ... #some lines of code

file1.funcCommon1 = file2FuncToReplacefuncCommon1

And now,

file1.funcCommon2()

Will use your "renewed" function. Again, this is really not a sane way to do this, you really should reconsider and just pass a function as an argument.

Answered By: juanpa.arrivillaga
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.