Home > Blockchain >  Is there a way to change something and get it displayed in the original code I wrote?
Is there a way to change something and get it displayed in the original code I wrote?

Time:07-20

Imagine I have this string

harry_potter = '''
    Mr. and Mrs. Dursley, of number four, Privet Drive, were
    proud to say that they were perfectly normal, thank
    you very much. They were the last people you’d expect to be involved in anything strange or mysterious, because they just didn’t
    hold with such nonsense.
    Mr. Dursley was the director of a fi rm called Grunnings, which
    made drills. He was a big, beefy man with hardly any neck, although he did have a very large mustache. Mrs. Dursley was thin
    and blonde and had nearly twice the usual amount of neck, which
    came in very useful as she spent so much of her time craning over
    garden fences, spying on the neighbors. The Dursleys had a small
    son called Dudley and in their opinion there was no fi ner boy
    anywhere.
    The Dursleys had everything they wanted, but they also had a
    secret, and their greatest fear was that somebody would discover it. 
'''

It's pretty big right, ok let's say I removed the word "Dursleys" from the string globally. Well, that only changes in the memory but my code is as it is. So, is there an way to change something and run it, it also changes in my code?

CodePudding user response:

As noted in the comment by @harsha_biyani you would have to read the source file and the write the change back. This is not a good design!

The string harry_potter is data. Data should not be persisted in code. That is what we have databases and data files for. So a better design would be to put the string in a text file, read the file, change the string and write the file back. There are many ways of doing this, but you could model it in class and abstract all the file handling there.


class HarryPotter:
    def __init__(self, filename: str):
        self.filename = filename
        with open(filename, 'r') as file:
            self._data = file.readlines()

    def __str__(self):
        return ''.join(self._data)

    def update(self, data: str):
        self._data = [line   '\n' for line in data.split('\n')]

    def save(self):
        with open(self.filename, 'w') as file:
            file.writelines(self._data)


if __name__ == '__main__':
    harry = HarryPotter('harry_potter.txt')

    print(str(harry))

    harry.update(str(harry).replace('Dursley',''))

    print(harry)

    harry.save()

        

CodePudding user response:

as other said, it is not a good idea, but you can do it, at least with byteplay, it is very powerful https://pypi.org/project/byteplay3/

The idea is that it will help us modify the "compiled"(Im not sure) code to whatever you want when the code executed

about the example, you can flip the result at run time, I think it is a piece of cake for this lib for your solution

>>> def f(a, b):
... print(a, b)
...
>>> f(3, 5)
3 5
>>> from byteplay3 import *
>>> # convert the code object of function f to a Code object
>>> c = Code.from_code(f.__code__)
>>> c
<byteplay3.Code object at 0x1030da3c8>
>>> # display the bytecode tuples in the Code object
>>> print( c.code )
2 1 LOAD_GLOBAL print
2 LOAD_FAST a
3 LOAD_FAST b
4 CALL_FUNCTION 2
5 POP_TOP
6 LOAD_CONST None
7 RETURN_VALUE

# Ok, now let's play! Say we want to change the function so it prints its
arguments in reverse order. To do this, we will insert a ROT_TWO opcode
after the two arguments were loaded to the stack. (That is, after
LOAD_FAST b and before CALL_FUNCTION 2.)::

>>> c.code[4:4] = [(ROT_TWO,None)]

# Then replace the code object in function f with a new one::

>>> f.__code__ = c.to_code()
>>> f(3,5)
5 3
  • Related