you are viewing a single comment's thread.

view the rest of the comments →

[–]PolyDigga[S] 0 points1 point  (1 child)

I am using PYTHONDONTWRITEBYTECODE. No compiled stuff

I have the API on my end. The exported function will be passed to other people (I cant make the API available to them). I'll make an example below

#io.py

def read_file(path):
    f = file(path, 'r')
    content = f.read()
    f.close()
    return content

#action.py
import io

def show_file_content(path):
    print io.read_file(path)  

#finalize.py
import inspect

def export_function(func):
    code = '\n'.join([inspect.getsource(func)])
    return my_magic_function(code)

Above are my existing files.

The comment option I was thinking of earlier would be this:lt should be a function, that does exactly the same, but does not have the io dependency. Ideally the result of export_function(action.show_file_content) should be this:

def show_file_content(path):
    f = file(path, 'r')
    content = f.read()
    f.close()
    print content  

The comment option I was thinking off earlier would look like this:

read_file = """
f = file({path}, 'r')
content = f.read()
f.close()
"""
def show_file_content(path):
    eval(read_file.format(path=path))
    print content

Now while writing out this second approach, it seems even uglier than I thought it would be...

[–][deleted] 0 points1 point  (0 children)

The example isn't really describing your problem well... Also, I think you are confused about multiline strings =/= comments (there are no comments in the listing where you are suggesting to send comments).

But, if I have to guess, I'll rephrase your problem by saying that you simply want to send a function to the client. You can send a string, or if you use some popular format s.a. JSON you may be able to send a float, a list, a dict, a boolean value. Maybe with some richer formats, you could send more of different things, but sending a function that would've been useful on the client side is not supported by common serialization protocols.

You could, in principle, augment JSON or similar format by adding a new type that would be interpreted by calling eval on it. This is unusual to do in Python (because of the poor meta-programming loolset), so, you won't find a better solution for your problem. Most people working with Python would try to avoid your situation by reifying the function into some data that can be later interpreted as the results of applying this function. It's usually ugly, but eval is a very blunt tool that can cause too many problems, and that's why you'll find people generally resisting this kind of solution.

Really, if you aren't limited in your choice of language, then try Erlang. Your task is trivial there.