Python locals()

Python’s locals() function returns a dictionary of name --> object mappings. The names are the ones defined in the current local scope, i.e., defined within the current module, class, method, or function—whatever the most local scope is. The objects are the values associated to these names. For example, if you set variable x = [1, 2, 3] in your local function scope, the locals() dictionary will contain a name 'x' and an object reference to [1, 2, 3].

Python locals() visual guide

Related Tutorial: Namespaces Made Simple

Usage Examples

Learn by example! Here’s a formatted example of how to use the locals() built-in function:

def f():
    x = [1, 2, 3]
    print(locals())

x = 42
f()
# {'x': [1, 2, 3]}

Within the local scope of function f, you define a new variable named 'x' and set it to the list object [1, 2, 3]. You also define another variable x = 42 on the global module level, not within a local function scope. If you call the locals() function within the function, it returns the dictionary of name --> object mappings. Among the mappings in the dictionary, you find the mapping 'x': [1, 2, 3]. Thus, the local scope of the function trumps the global module-level scope.

You can also modify a global variable using the locals() dictionary:

>>> friend = 'Alice'
>>> locals()['friend'] = 'Bob'
>>> friend
'Bob'

This is useful if you want to modify some dynamic variables that you don’t yet know at programming time. For example, you want the user to give you a string of a variable to update. Your program only has the string, so the only way to update the associated global name is to use the locals() dictionary.

Video locals()

So, how does the syntax formally look like?

Syntax locals()

You use the locals() method without an argument.

Syntax: 
locals()      # Returns dictionary of name --> object pairs defined in your local scope.
Arguments-
Return ValuedictReturns the dictionary of (name –> object) mappings of all names you can use in the local scope—e.g., within a function or a method. This includes the name you defined in the local scope but not the names defined in the global scope.

Python locals() Return Value

Returns the dictionary of (name –> object) mappings of all names you can use in the local scope—e.g., within a function or a method. This includes the name you defined in the local scope but not the names defined in the global scope.

l = locals()
print(type(l))
# <class 'dict'>

Python locals() Interactive Shell Exercise

Let’s have a practical example how to use the locals() function in a real application that asks the user to type in any variable to check its current value:

Python locals() example "Run"

Exercise: Guess the output of this code snippet—which name is in the locals() dictionary? Then run the code & check your result!


But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners


Solution: The interactive exercise results in the locals dictionary with the name 'Liz' because when locals() is called, the most local definition of the name was 'Liz'.

Summary

Python’s locals() function returns a dictionary of name --> object mappings.

  • The names are the ones defined locally, i.e., defined within your current local scope (e.g., functions).
  • The objects are the values associated to these names.

For example, if you set variable x = [1, 2, 3], the locals() dictionary will contain a name 'x' and an object reference to [1, 2, 3].

def f():
    x = [1, 2, 3]
    print(locals())

x = 42
f()
# {'x': [1, 2, 3]}

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!