Suppose, we have 3 files:
library1.py:
SomeVariable = '1'
library2.py:
import library1
print(library1.SomeVariable)
library3.py:
SomeVariable = '2'
my goal is to "change" library1 import(not only 1 variable) in library2.py so result output will be '2' (in other words,replace cache of library1 in library2.py to library3)
CodePudding user response:
WARNING: This method is very hacky, and you might probably will break things.
Let's say we have this library1.py
:
var1 = 100
var2 = 'never gonna give you up'
a = 3.1415926
And, we want to overwrite it with overwrite.py
:
var1 = -9999
var2 = 'never gonna let you down'
a = 2.71828
If we go into a shell, we can see that a module has a __dict__
attribute that holds everything it has inside of it.
>>> import library1
>>> library1.__dict__
# NOTE: This also contains a bunch of python's variables, including their builtins, magic things like `__name__`, etc
# I cut them out for simplicity
{'var1': 100, 'var2': 'never gonna give you up', 'a': 3.1415926}
This is nice, since we can use this to access the attributes without really accessing them:
>>> import library1
>>> library1.__dict__['a'] = 'never gonna run around and desert you'
>>> library1.a
'never gonna run around and desert you'
>>> library1.__dict__['this_variable_wasnt_even_defined'] = 'never gonna make you cry'
>>> library1.this_variable_wasnt_even_defined
'never gonna make you cry'
We don't want to overwrite any magic (starting and ending with two underscores) attributes, so:
>>> def is_magic(name: str) -> bool:
... return name[0] == '_' and name[1] == '_' and name[-1] == '_' and name[-2] == '_'
>>> is_magic('not_very_magic_variable')
False
>>> is_magic('__name__')
True
>>> is_magic('__init__')
True
We also don't want to overwrite any builtin functions:
>>> def is_builtin(obj: object) -> bool:
... builtin_type = type(print)
... return obj.__class__ is builtin_type
...
>>> is_builtin(print)
True
>>> is_builtin(open)
True
This is where it all comes together.
We use values in library3
to overwrite the __dict__
of library1
.
>>> from utils import is_builtin, is_magic
>>> import library1
>>> import overwrite
>>>
>>> for key, value in overwrite.__dict__.items():
... if is_magic(key):
... continue
... if is_builtin(value):
... continue
... # otherwise, we have something to overwrite
... library1.__dict__[key] = value
... print(f'I have overwritten {key} with {value}')
...
I have overwritten var1 with -9999
I have overwritten var2 with never gonna let you down
I have overwritten a with 2.71828
You can see that library1
has been overwritten:
# ...
>>> library1.var1
-9999
>>> library1.var2
'never gonna let you down'
>>> library1.a
2.71828
CodePudding user response:
I found one way to do that:
import library1,library2,library3
import importlib
for i in library3.__dict__.keys():
library1.__dict__[i] = library3.__dict__[i]
library2 = importlib.reload(library2)
CodePudding user response:
You can use copy
import copy
b = copy.copy(lib1.a)
...
print(lib2.b)