Python: compile() function
compile() function
The compile() function is used to compile the source into a code.
The function raises SyntaxError if the compiled source is invalid, and TypeError if the source contains null bytes.
Syntax:
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Version:
(Python 3.2.5)
Parameter:
Name | Description | Required / Optional |
---|---|---|
source | A normal string, a byte string, or an AST object | Required |
filename | The name of the file file from which the code was read. If it wasn't read from a file, you can give a name yourself | Required |
mode | Either exec or eval or single. | Required |
flags | Controls which future statements affect the compilation of the source. Default Value: 0 | Optional |
dont-inherit | How to compile the source. Default False | Optional |
optimize | Optimization level of the compiler. Default value -1. | Optional |
Return value:
The filename argument should give the file from which the code was read; pass some recognizable value if it wasn't read from a file ('<string>' is commonly used).
Example: Python compile() function
codeInString = 'x = 8\ny=5\nsum=x+y\nprint("sum =",sum)'
codeObejct = compile(codeInString, 'sumstring', 'exec')
exec(codeObejct)
Output:
sum = 13
Python Code Editor:
Previous: classmethod()
Next: complex()
Test your Python skills with w3resource's quiz
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python/built-in-function/compile.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics