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

10
  • So where's the code? Commented Nov 20, 2015 at 11:55
  • can you put some input and output plz? Commented Nov 20, 2015 at 11:55
  • docs.python.org/2/library/marshal.html Commented Nov 20, 2015 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? Commented Nov 20, 2015 at 12:01
  • Your code write <function make_route.<locals>.welcome at 0x7fd2c9cf59d8> into the file, so what do you mean about default repr ? Commented Nov 20, 2015 at 12:03

1 Answer 1

-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
Sign up to request clarification or add additional context in comments.

1 Comment

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.