Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

Python built-in function "compile". What is it used for?

I came across a built-in function compile today. Though i read the documentation but still do not understand it's usage or where it is applicable. Please can anyone explain with example the use of this function. I will really appreciate examples.

From the documentation, the function takes some parameters as shown below.

compile(source, filename, mode[, flags[, dont_inherit]])
question from:https://stackoverflow.com/questions/22443939/python-built-in-function-compile-what-is-it-used-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is not that commonly used. It is used when you have Python source code in string form, and you want to make it into a Python code object that you can keep and use. Here's a trivial example:

>>> codeobj = compile('x = 2
print "X is", x', 'fakemodule', 'exec')
>>> exec(codeobj)
X is 2

Basically, the code object converts a string into an object that you can later call exec on to run the source code in the string. (This is for "exec" mode; the "eval" mode allows use of eval instead, if the string contains code for a single expression.) This is not a common task, which is why you may never run across a need for it.

The main use for it is in metaprogramming or embedding situations. For instance, if you have a Python program that allows users to script its behavior with custom Python code, you might use compile and exec to store and execute these user-defined scripts.

Another reason compile is rarely used is that, like exec, eval, and their ilk, compile is a potential security hole. If you take user code in string form and compile it and later exec it, you could be running unsafe code. (For instance, imagine that in my example above the code was formatYourHardDrive() instead of print x.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...