English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations sur les fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemple de compile() en Python

Python built-in functions

La méthode compile() retourne un objet de code Python à partir du code source (chaîne ordinaire, chaîne de bytes ou objet AST).

La syntaxe de compile() est :

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=)}-1)

If the Python code is in string form or is an AST object, and you want to change it to a code object, use the compile() method.

can be used later such asexec() and eval()Class methods to call the code object returned by compile() method, which will execute the dynamically generated Python code.

compile() parameters

  • source -Normal string, byte string, or AST object

  • filename-The file from which the code is read. If not read from a file, it can be named itself

  • mode- exec or eval or single.

    • eval -Accepts only one expression.

    • exec -It can use a code block with Python statements, classes, and functions, etc.

    • single -If it contains a single interactive statement

  • flags (optional) and dont_inherit (optional)-Specify which statements in the future will affect the compilation of the source code. Default value: 0

  • optimize (optional)-The optimization level of the compiler. Default value-1.

compile() return value

The compile() method returns a Python code object.

Example: How does compile() work?

codeInString = 'a =', 5\nb=6\nsum=a+b\nprint("sum =",sum)'
codeObejct = compile(codeInString, 'sumstring', 'exec')
exec(codeObejct)

When running the program, the output is:

sum = 11

Here,source (source)is in the form of a normal string. ThisFilenameissumstringAnd the exec mode later allows the use of the exec() method.

The compile() method converts a string into a Python code object. Then the code object is executed using the exec() method.

Python built-in functions