Self-modifying Code

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • qwweeeit@yahoo.it

    Self-modifying Code

    Hi all,

    when I was young I programmed in an interpreted language that allowed
    to modify itself.
    Also Python can (writing and running a module, in-line):

    fNew =open("newModul e.py",'w')
    lNew=['print 123\n','print 454\n','print 789\n']
    fNew.writelines (lNew)
    fNew.close()
    from newModule import *

    Running this small example it correctly displays:
    123
    456
    789

    Did you know? Certainly someone has already discovered and applied
    that, because the applications are several (think only to the
    possibility of reducing code length by eliminating the coding of false
    alternatives, or the possibility to convert a list of instructions
    taken somewhere in a running code...)

    Bye.

  • Dennis Benzinger

    #2
    Re: Self-modifying Code

    qwweeeit@yahoo. it schrieb:[color=blue]
    > [...]
    > Also Python can (writing and running a module, in-line):
    >
    > fNew =open("newModul e.py",'w')
    > lNew=['print 123\n','print 454\n','print 789\n']
    > fNew.writelines (lNew)
    > fNew.close()
    > from newModule import *
    > [...][/color]

    You don't even need a file for this.
    Try: exec("print 123; print 456; print 789")

    Bye,
    Dennis

    Comment

    • Peter Hansen

      #3
      Re: Self-modifying Code

      qwweeeit@yahoo. it wrote:
      [regarding "self-modifying code"][color=blue]
      > fNew =open("newModul e.py",'w')
      > lNew=['print 123\n','print 454\n','print 789\n']
      > fNew.writelines (lNew)
      > fNew.close()
      > from newModule import *[/color]

      This isn't really self-modifying code (unless you are talking about this
      being a small part of a much larger application which is where the
      import actually occurs), but in any event neither is it the simplest way
      to do what you are trying to do using Python. The absolute simplest,
      which is largely equivalent to what you've done here, is simply "exec
      'print 123\nprint 456\nprint 789'". A close relative is the method
      provided by the execfile() standard function (avoiding the import).
      [color=blue]
      > Did you know? Certainly someone has already discovered and applied
      > that, because the applications are several (think only to the
      > possibility of reducing code length by eliminating the coding of false
      > alternatives, or the possibility to convert a list of instructions
      > taken somewhere in a running code...)[/color]

      Those same applications are better served, generally, by doing things
      like parameterizing function definitions on-the-fly, or by dynamically
      binding new methods into objects or classes. There are many recipes in
      the CookBook or the list archives showing how to do all these sorts of
      things.

      I'm afraid the technique you show above, while intriguing to a newcomer
      to Python, has a limited number of use cases, though if one needs to
      modify or generate some small part of a program for later use (requiring
      the basic persistence that your technique has), it is definitely a
      viable technique.

      -Peter

      Comment

      • Do Re Mi chel La Si Do

        #4
        Re: Self-modifying Code

        Hi, you, also !

        A view, with a little difference :


        def titi(par):
        if par>222:
        return par*2
        else:
        return par*10

        print titi(123)
        print titi(1234)

        #now, change the function, "on instant"
        txt="""def titi(par):
        if par>222:
        return str(par)*2
        else:
        return str(par)*5
        """
        exec(txt,global s(),globals())

        print titi(123)
        print titi(1234)






        Michel Claveau



        Comment

        • Steven D'Aprano

          #5
          Re: Self-modifying Code

          On Thu, 19 May 2005 21:49:46 +0200, Do Re Mi chel La Si Do wrote:
          [color=blue]
          > Hi, you, also !
          >
          > A view, with a little difference :
          >
          >
          > def titi(par):
          > if par>222:
          > return par*2
          > else:
          > return par*10
          >
          > print titi(123)
          > print titi(1234)
          >
          > #now, change the function, "on instant"
          > txt="""def titi(par):
          > if par>222:
          > return str(par)*2
          > else:
          > return str(par)*5
          > """
          > exec(txt,global s(),globals())
          >
          > print titi(123)
          > print titi(1234)[/color]


          Self-modifying code is almost always a TERRIBLE idea. Using exec is
          dangerous unless you can control what is being executed. Using exec on
          code a user supplies is a huge security hole.

          Self-modifying code is one of those ideas that seems cute when you first
          learn about it, but in practice is a bad idea. It makes debugging your
          code much more difficult. It makes comprehending how your code works
          harder. Generally, you should avoid it, and shun code that modifies itself.

          Having said that, here is a good example of self-modifying code:



          The RingBuffer class dynamically modifies itself once it is full so that
          its behaviour changes.


          --
          Steven



          Comment

          • Do Re Mi chel La Si Do

            #6
            Re: Self-modifying Code

            Hi !


            I often use the auto-modification of code, to allow the users to adapt
            software to the evolution of their needs.

            When this technique is controlled, and framed well, it presents only few
            problems.

            AMHA, to speak about danger, it is the result of a lack of practice and
            tests. It is a little the same debate as: dynamic language versus static
            language.


            @-salutations

            Michel Claveau




            Comment

            • Bruno Desthuilliers

              #7
              Re: Self-modifying Code

              Steven D'Aprano a écrit :
              (snip)[color=blue]
              > Having said that, here is a good example of self-modifying code:
              >
              > http://aspn.activestate.com/ASPN/Coo...n/Recipe/68429
              >
              > The RingBuffer class dynamically modifies itself once it is full so that
              > its behaviour changes.
              >[/color]

              This is nothing more than a pythonic implementation of the state
              pattern. I would not call this "self-modifying code", since the code
              itself is not modified.

              Comment

              Working...