functions, optional parameters

Gregory Ewing greg.ewing at canterbury.ac.nz
Fri May 8 21:41:26 EDT 2015


Chris Angelico wrote:
> How do you know that the function's code
> object was created when compile() happened, rather than being created
> when the function was defined?

Python 3.4.2 (default, Feb 4 2015, 20:08:25)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> source = "def f(x = 42): pass"
 >>> code = compile(source, "", "exec")
 >>> c1 = code.co_consts[1]
 >>> c1
<code object f at 0x53d430, file "", line 1>
 >>> e = {}
 >>> exec(code, e)
 >>> c2 = e['f'].__code__
 >>> c2
<code object f at 0x53d430, file "", line 1>
 >>> c1 is c2
True
Is that proof enough for you?
-- 
Greg


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /