Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

12
  • 7
    This also applies to PyPy, up to the current version (1.8 at the time of this writing.) The test code from the OP runs about four times slower in global scope compared to inside a function. Commented Jun 28, 2012 at 17:17
  • 2
    @Walkerneo The primary conversation going on here is the comparison between local variable lookups within a function and global variable lookups that are defined at the module level. If you notice in your original comment reply to this answer you said "I wouldn't have thought global variable lookups were faster than local variable property lookups." and they're not. katrielalex said that, although local variable lookups are faster than global ones, even global ones are pretty optimized and faster than attribute lookups (which are different). I don't have enough room in this comment for more. Commented Jun 29, 2012 at 0:21
  • 3
    @Walkerneo foo.bar is not a local access. It is an attribute of an object. (Forgive the lack of formatting)def foo_func: x = 5, x is local to a function. Accessing x is local. foo = SomeClass(), foo.bar is attribute access. val = 5 global is global. As for speed local > global > attribute according to what I've read here. So accessing x in foo_func is fastest, followed by val, followed by foo.bar. foo.attr isn't a local lookup because in the context of this convo, we're talking about local lookups being a lookup of a variable that belongs to a function. Commented Jun 29, 2012 at 1:57
  • 4
    @thedoctar have a look at the globals() function. If you want more info than that you may have to start looking at the source code for Python. And CPython is just the name for the usual implementation of Python -- so you probably are using it already! Commented Jul 6, 2012 at 14:45
  • 2
    Yes, and because most of the time the slight slowness isn't actually important to the running speed of the program. Commented Oct 25, 2017 at 20:12