Daftar Referensi Python
compile() mengompilasi source menjadi objek code untuk eval() atau exec().
Sintaks
compile(source, filename, mode,
flags=0, dont_inherit=False, optimize=-1)
Parameter
| Parameter | Wajib? | Keterangan |
|---|---|---|
source |
Ya | String, bytes, atau AST |
filename |
Ya | Nama untuk pesan error |
mode |
Ya | exec, eval, atau single |
flags |
Tidak | Compiler flags |
dont_inherit |
Tidak | Tidak mewarisi flags |
optimize |
Tidak | Level optimasi -1 sampai 2 |
Nilai balik: objek code.
Contoh
kode = compile("2 + 3", "<teks>", "eval")
print(eval(kode))
Output:
5
Contoh Lainnya
Mode exec
kode = compile("x = 7\nprint(x)", "<teks>", "exec")
exec(kode)
Output:
7
Memeriksa tipe hasil
kode = compile("10", "<teks>", "eval")
print(type(kode).__name__)
Output:
code
Menangani sintaks salah
try:
compile("if", "contoh.py", "exec")
except SyntaxError:
print("sintaks salah")
Output:
sintaks salah
Kesalahan Umum
- Mode harus sesuai source.
- Source tidak tepercaya tidak aman untuk
eval()/exec(). - Sintaks salah menghasilkan
SyntaxError.
Pelajari Lebih Lanjut
- Referensi: eval() · callable()
