The compile () function returns a code object in Python from the specified source, be it a normal string, byte string or AST object. How is the syntax of compile () function, what parameters does it have and how to use it? Invites you to read the track.
The compile () function syntax in Python
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
The compile () function uses when your Python code is in the form of strings or AST and you want to convert it to an object code.
The object code converted with compile () will be invoked by the program by exec () and eval ().
The parameters of compile function ()
Return value from compile ()
The compile () function returns a code object in Python.
Example: How does the compile () function work?
Follow the following example:
codeInString = 'a = 5nb=6nsum=a+bnprint("sum =",sum)'
codeObejct = compile(codeInString, 'sumstring', 'exec')
exec(codeObejct)
Run the program, the result is:
sum = 11
In the above example, the source here is a normal string, filename is sumstring, mode is exec after conversion, you can use the exec () function to call the resulting code object.
You can see a list of built-in Python functions and don't forget to do Python exercises to reinforce your knowledge.
Previous lesson: complex () function in Python
Next article: Function delattr () in Python
ncG1vNJzZmismaXArq3KnmWcp51kwamxjJympqiZobJustSnmq2hn6N6qrqMqbCtoJ%2Bj