functions, optional parameters

Chris Angelico rosuav at gmail.com
Fri May 8 13:49:36 EDT 2015


On Sat, May 9, 2015 at 3:36 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sat, 9 May 2015 02:02 am, Chris Angelico wrote:
>> Aside from constructing two closures in the same context and proving
>> that their __code__ attributes point to the same object, is there any
>> way to distinguish between "code object compilation time" and "def
>> execution time"? I just played around with it, and as far as I can
>> tell, code objects are completely read-only.
>
> Sure there is. Write this Python code:
>
> py> source = """\
> ... print "Function definition time."
> ... def func():
> ...     pass
> ... """
> py> print "Compile time."; code = compile(source, '', 'exec')
> Compile time.
> py> exec(code)
> Function definition time.

Yes, but can you *distinguish* them in terms of default argument
versus code object creation? How do you know that the function's code
object was created when compile() happened, rather than being created
when the function was defined? Is there anything that lets you in any
way show different behaviour based on that timing difference?

ChrisA



More information about the Python-list mailing list