0

I've made a function that will create functions and write them to a file but the problem is they write to the file as the default repr. How can I write them to a file as a normal function?

def make_route(title):
    test = 1
    def welcome():
        return test + 1

    welcome.__name__ = title 
    with open('test2.py', 'a') as f:
        f.write('\n%s\n' % (welcome))

    return welcome

I need it to write

def welcome():
    return test + 1

to the file

  • So where's the code? – Remi Guan Nov 20 '15 at 11:55
  • can you put some input and output plz? – Iman Mirzadeh Nov 20 '15 at 11:55
  • https://docs.python.org/2/library/marshal.html – Ignacio Vazquez-Abrams Nov 20 '15 at 11:55
  • 3
    Writing functions to a file doesn't make much sense. Can you explain more specifically what you actually want to accomplish? – TigerhawkT3 Nov 20 '15 at 12:01
  • Your code write `.welcome at 0x7fd2c9cf59d8>` into the file, so what do you mean about *default repr* ? – Remi Guan Nov 20 '15 at 12:03
  • @KevinGuan Yeah I've added some source code, I just had to simplify my original post, I posted prematurely by accident. –  Nov 20 '15 at 12:04
  • That edit doesn't help much. Again, what do you actually want to accomplish? Do you want to write the function's source code to a file? Or its bytecode, perhaps? – TigerhawkT3 Nov 20 '15 at 12:04
  • @TigerhawkT3 Yeah sorry, I want to write the source code. –  Nov 20 '15 at 12:08
  • More possible duplicates [here](http://stackoverflow.com/questions/4014722/viewing-the-code-of-a-python-function) and [here](http://stackoverflow.com/questions/1562759/can-python-print-a-function-definition). Just Google SO for "python function source code." – TigerhawkT3 Nov 20 '15 at 12:16
  • @TigerhawkT3 Thanks I just returned a string in the end I was just curious if there was a more elegant way but thankyou. –  Nov 20 '15 at 12:30

1 Answers1

-1

you need to serialize your function using marshal

import marshal
def f(x): return 2*x
saved = marshal.dumps(f.func_code)

then you can use saved string:

import marshal, types
code = marshal.loads(saved)
f= types.FunctionType(code, globals(), "your_name")

f(10)  #returns 20
Iman Mirzadeh
  • 12,710
  • 2
  • 40
  • 44
  • 1
    Unfortunately, this doesn't answer the question, which demonstrates why it's generally better to hold off on answering until the question is more clear. – TigerhawkT3 Nov 20 '15 at 12:17