Tag: Scoping & namespaces

  • LEGB? Meet ICPO, Python’s search strategy for attributes

    When it comes to variables, Python has a well-known search strategy, known by the acronym “LEGB.” Whenever you mention a variable — and by “variable,” I mean a name that could be referencing data, a function, or a class — Python tries to find it in four different places: The local (function) scope, the enclosing…

    Read more

  • foo(y=y), and similar code that confuses Python newbies

    Let’s define a simple Python function: In [1]: def foo(x): …: return x * x …: In [2]: foo(5) Out[2]: 25 In [3]: foo(10) Out[3]: 100 As we can see, this function has a single parameter, “x”.  In Python, parameters are local variables whose values are set by whoever is calling the function. So we…

    Read more

  • 2+2 might be 4, but what is True+True?

    In Python, we know that we can add two integers together: >> 2 + 2 4 And of course, we can add two strings together: >> ‘a’ + ‘b’ ‘ab’ We can even add two lists together: >> [1,2,3] + [4,5,6] [1, 2, 3, 4, 5, 6] But what happens when you add two booleans…

    Read more

  • Fun with Python scoping rules

    Let’s say I want to try something on a list in Python.  While I usually like to call my test list objects “mylist”, I sometimes forget, and create a variable named “list”: list = [‘a’, ‘b’, ‘c’] If you’re like me, then you might not immediately notice that you’ve just defined a variable whose name…

    Read more