[CentralOH] Python interpretor question

Mark Erbaugh mark at microenh.com
Thu Apr 21 00:48:22 CEST 2011


Hello,

I'm trying to get my head around what happens when in a Python program

Consider a trivial example

def f1(x):
	fmt1 = "%d"
	return fmt1 % x


fmt2 = "%d"
def f2(x):
	return fmt2 % x


I believe both functions produce the same results. The question is how Python goes about it.

Here's my understanding of what happens:

When the module containing this code is imported, module namespace entries are created for f1, f2 and fmt2.

When f1 is called, a f1 namespace entry for fmt1 is created then the combined namespaces are searched for fmt1 finding it in the f1 namespace.  When f1 returns the f1 namespace is destroyed.

When f2 is called, the combined namespaces are searched for fmt2, finding it in the module namespace.

Is it correct that every time f1 is called, the fmt1 = "%d" is processed to add fmt1 to the f1 namespace, but fmt2 is only added (to the module namespace) once?

If so, it seems that while f1 results in less pollution of the module namespace, it would be slightly less efficient. Is this correct?

Would the same logic apply if f1 and f2 were methods in a class?

Thanks,
Mark


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20110420/36c34617/attachment.html>


More information about the CentralOH mailing list