Context: I want to replace an object with another:
x = []
r = [2]
replace(x, r)
assert x == [2]
assert x is r
In Smalltalk this would be called become .
Question: How would I do that? Would I need to create a C-extension or is there already something like this?
I tried: This But I need to handle so many cases. Just changing the object behind the pointer would be enough for me.
Reason: I want to implement extensions like features, refinements and subjects. Sometimes I can not change the class of an builtin object os.__class__ = X to enable more flexibility. Since I can not do that, I though about replacing.
Concrete Example of Usage:
A subjective view:
import pylung
pylung.deutsch()
import os # I want to preserve object identity with the original os
os.ERREICHE_SETZEN
os.durchlaufe(...)
A translation:
import os
import pylung
os = pylung.translate(os, 'deutsch') # German
@os.walk
def durchlaufe(ordner, oben_nach_unten, folge_links):
"""Ordner baum erzeuger
"""
A simple = does what you want:
x = []
r = [2]
x = r
assert x == [2]
assert x == r
assert x is r
If you want to be able to do this...
import pylung
pylung.deutsch()
import os # I want to preserve object identity with the original os
os.ERREICHE_SETZEN
os.durchlaufe(...)
...and retain compatibility with existing libraries (which will use the English names), it's probably easiest to add additional attributes to the os module, rather than replacing them. For example...
# pylung.py
def deutsch():
import os
os.durchlaufe = os.walk
# etc...
...if you also want to translate module names, say collections to kollektionen, you can do something like this...
# pylung.py
import sys
def deutsch():
import os
os.durchlaufe = os.walk
# etc...
import collections
sys.modules['kollektionen'] = sys.modules['collections']
...again, ensuring you keep the original module name in place for compatibility.
You could also look at using a custom import hook to do the module translations on-demand, so you need only replace the symbols that are actually used in the script.
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