Search code examples
stringpython-3.xvariable-assignmentnaming-conventionssymbol-table

variable names based on a parsed string


I want to name my variable based on a parsed in string.

For example: if parsed in string == 'dog': my variable name should be equal to dog and its value the string 'dog'


Solution

  • This answer to inform about symbol tables in python helps to directly answer the question:

    >>> varname = 'spam'
    >>> value = 'eggs'
    >>> locals()
    {'__builtins__': <module 'builtins' (built-in)>, 'varname': 'spam', 'value': 'eggs', '__package__': None, '__name__': '__main__', '__doc__': None}
    >>> locals()[varname] = value
    >>> locals()
    {'__builtins__': <module 'builtins' (built-in)>, 'varname': 'spam', 'spam': 'eggs', 'value': 'eggs', '__package__': None, '__name__': '__main__', '__doc__': None}
    >>> print(spam)
    some value
    

    locals() provides a dict of the locally visible variables. And by modifying the dict, you can change and create new variables. Python documentation here

    There is also a corresponding globals() to access the globally visible variables. Refer to this part of the python documentation to learn about the scope of variables.

    In the above context globals() yields a dict with the same content because in this case the local scope is the global. Inside a class, you'll see different content and you have to decide if you want to mangle the local scope or the global one.

    However, it is probably not such a good idea to do this kind of stuff unless you know what you are doing. You could create objects of a self-defined class which have a name attribute - depends on what you intend to do