[CentralOH] Python interpretor question
jonebird at gmail.com
Thu Apr 21 02:12:32 CEST 2011
In short, yes, I would agree that f2() is quicker than f1() but not
for the same reason. :-)
I would change your description from saying that "the combined
namespaces are searched" to "the current namespace is searched, and
then the parent namespace is searched, and so on until the reference
is satisfied". Think of the namespaces as nested like the blocks of
code. In both print statements, the functions f1 and f2 are searching
their current namespace but only during the f2() block does the
variable resolution have to look outside to the parent namespace, so
technically the reference lookup is quicker in the f1() block.
The reason I say f2() would be quicker is because of the repeated
creating and deleting of the fmt1 variable in f1(). Without testing, I
think it's safe to say that namespace searching, especially in this
small example, would be much quicker than the work needed to create &
destroy the formatting string.
-- Jon Miller
On Wed, Apr 20, 2011 at 6:48 PM, Mark Erbaugh <mark at microenh.com> wrote:
> 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?
> CentralOH mailing list
> CentralOH at python.org
More information about the CentralOH