functions, optional parameters

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri May 8 13:36:32 EDT 2015


On Sat, 9 May 2015 02:02 am, Chris Angelico wrote:

> On Sat, May 9, 2015 at 1:48 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>> On May 8, 2015 9:26 AM, "Steven D'Aprano"
>> <steve+comp.lang.python at pearwood.info> wrote:
>>>
>>> Do you think that Python will re-compile the body of the function every
>>> time
>>> you call it? Setting the default is part of the process of compiling the
>>> function.
>>
>> To be a bit pedantic, that's not accurate. The default is evaluated when
>> the function object is created, i.e. when the def statement is executed
>> at runtime, not when the underlying code object is compiled.
> 
> 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:


# test.py
print("Function definition time.")
def func():
    pass


Now from your shell, run this:


echo "Compile time"
python -m compileall test.py
rm test.py
sleep 5
python test.pyc



(The sleep is just to make it clear that the compilation and definition time
can be very far apart. They could literally be years apart.)



Actually, we don't need external tools, we can do it all in Python!

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.




-- 
Steven




More information about the Python-list mailing list