Search code examples
pythonpython-2.7naming-conventionsvariable-names

How to access the string stored in the variable? (Python)


Since my last question was rather poorly worded, here is a different question that will provide me the same benefits!

First of all, I want to accomplish one thing: create a new Set and set that Set's name to the value of a variable (a string I would set it equal to, e.g. new_set_name = 'buffalo')

I want it to be something like this new_set_name = Set([]) Except I don't want the end result to be a Set with the name new_set_name I want the name of the Set to instead be: buffalo.

I tried quite hard to make this as non-confusing as possible, but if it is, let me know! I will try to fix it!


Solution

  • You can create a variable in the module namespace like so

    new_set_name = 'buffalo'
    globals()[new_set_name] = set()
    

    Namespaces are implemented by dicts but python figures out context when you use the variables so you don't have to refer to them directly. You can view or update at other module namespaces using their __dict__ variable but its more customary to use setattr

    import os
    print(os.__dict__)
    os.__dict__[new_set_name] = set()
    setattr(os, new_set_name, set())