Another way to extend (in particular, add new methods, rather than modify existing) classes, even built-in ones, is to use a preprocessor that adds the ability to extend the scope of Python itself or go beyond it, converting the extension to normal Python syntax before Python will really see it.
I did this to extend the Python 2 class str() , for example. str() is a particularly interesting target because of the implicit connection to the data in quotation marks, such as 'this' and 'that' .
Here is some extensible code in which the only non-Python syntax added is the extend:testDottedQuad :
extend:testDottedQuad def testDottedQuad(strObject): if not isinstance(strObject, basestring): return False listStrings = strObject.split('.') if len(listStrings) != 4: return False for strNum in listStrings: try: val = int(strNum) except: return False if val < 0: return False if val > 255: return False return True
Then I can write in the code passed to the preprocessor:
if '192.168.1.100'.testDottedQuad(): doSomething() dq = '216.126.621.5' if not dq.testDottedQuad(): throwWarning(); dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad() if dqt: print 'well, that was fun'
The preprocessor eats this, spits out normal Python without patches for monkeys, and Python does what I intended to do.
Just as an ac preprocessor adds functionality to c, so a Python preprocessor can add functionality to Python.
My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.
fyngyrz May 08 '19 at 3:41 pm 2019-05-08 15:41
source share