Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6807983
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T19:53:57+00:00 2026-05-26T19:53:57+00:00

How do you dynamically set local variable in Python (where the variable name is

  • 0

How do you dynamically set local variable in Python (where the variable name is dynamic)?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T19:53:58+00:00Added an answer on May 26, 2026 at 7:53 pm

    Contrary to other answers already posted you cannot modify locals() directly and expect it to work.

    >>> def foo():
        lcl = locals()
        lcl['xyz'] = 42
        print(xyz)
    
    
    >>> foo()
    
    Traceback (most recent call last):
      File "<pyshell#6>", line 1, in <module>
        foo()
      File "<pyshell#5>", line 4, in foo
        print(xyz)
    NameError: global name 'xyz' is not defined
    

    Modifying locals() is undefined. Outside a function when locals() and globals() are the same it will work; inside a function it will usually not work.

    Use a dictionary, or set an attribute on an object:

    d = {}
    d['xyz'] = 42
    print(d['xyz'])
    

    or if you prefer, use a class:

    class C: pass
    
    obj = C()
    setattr(obj, 'xyz', 42)
    print(obj.xyz)
    

    Edit:
    Access to variables in namespaces that aren’t functions (so modules, class definitions, instances) are usually done by dictionary lookups (as Sven points out in the comments there are exceptions, for example classes that define __slots__). Function locals can be optimised for speed because the compiler (usually) knows all the names in advance, so there isn’t a dictionary until you call locals().

    In the C implementation of Python locals() (called from inside a function) creates an ordinary dictionary initialised from the current values of the local variables. Within each function any number of calls to locals() will return the same dictionary, but every call to locals() will update it with the current values of the local variables. This can give the impression that assignment to elements of the dictionary are ignored (I originally wrote that this was the case). Modifications to existing keys within the dictionary returned from locals() therefore only last until the next call to locals() in the same scope.

    In IronPython things work a bit differently. Any function that calls locals() inside it uses a dictionary for its local variables so assignments to local variables change the dictionary and assignments to the dictionary change the variables BUT that’s only if you explicitly call locals() under that name. If you bind a different name to the locals function in IronPython then calling it gives you the local variables for the scope where the name was bound and there’s no way to access the function locals through it:

    >>> def foo():
    ...     abc = 123
    ...     lcl = zzz()
    ...     lcl['abc'] = 456
    ...     deF = 789
    ...     print(abc)
    ...     print(zzz())
    ...     print(lcl)
    ...
    >>> zzz =locals
    >>> foo()
    123
    {'__doc__': None, '__builtins__': <module '__builtin__' (built-in)>, 'zzz': <built-in function locals>, 'foo': <function foo at 0x000000000000002B>, '__name__': '__main__', 'abc': 456}
    {'__doc__': None, '__builtins__': <module '__builtin__' (built-in)>, 'zzz': <built-in function locals>, 'foo': <function foo at 0x000000000000002B>, '__name__': '__main__', 'abc': 456}
    >>>
    

    This could all change at any time. The only thing guaranteed is that you cannot depend on the results of assigning to the dictionary returned by locals().

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What is the best way to dynamically set the 'order by' column name and
Is there a way to dynamically set the ListId field in the ListView control.
Using jQuery , how can I dynamically set the size attribute of a select
Is it possible to create a new List<T> where the T is dynamically set
Is it possible to make changes to a CSS rule-set dynamically (i.e. some JS
I'm trying to dynamically create a set of labels in my XUL Runner application.
I'm trying to model bind a set of dynamically generated checkboxes so as to
How to set cell/column value dynamically using PHPExcel library? I am fetching result set
I need to set the text within a DIV element dynamically. What is the
I have a set of WCF web services connected to dynamically by a desktop

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.