Question Details

No question body available.

Tags

python python-typing python-internals

Answers (2)

Accepted Answer Available
Accepted Answer
March 1, 2026 Score: 4 Rep: 368 Quality: High Completeness: 70%

The code object actually does not work when you run it:

>>> exec(code)
Traceback (most recent call last):
  File "", line 1, in 
    exec(code)
    ~~~~^^^^^^
  File "", line 1, in 
TypeError: list expected at most 1 argument, got 5

compile(...) only checks if the syntax is correct, and does not determine immediately if the parameters are valid.

The other snippet works when runned, but not as expected. The object l2 turns out to be a generic alias:

>>> exec(code2)
>>> l2
list[1, 2, 3, 4, 5]
>>> type(l2)

March 1, 2026 Score: 2 Rep: 464 Quality: Low Completeness: 50%

There are two different things happening here.

1) compile() only checks syntax

compile() parses the code and generates bytecode.
It does not execute it and does not validate function signatures.

So this compiles fine:

compile('l = list(1, 2, 3, 4, 5)', '', 'exec')

because list(1, 2, 3, 4, 5) is syntactically valid. The TypeError (“expected at most 1 argument”) happens at runtime, not at compile time.

You can even compile:

compile('l = somerandomname(1,2,3)', '', 'exec')

Name resolution also happens at runtime.

Only invalid syntax fails:

compile('a ds 2 d', '', 'exec') #syntaxError

2) list(…) vs list[…]

list[1,2,3,4,5] is valid code, but is defining a type, not creating a list