-1

I want to make a variable with help of a function that gets its name from an argument, so that if I run this;

hi_var(abc)
print(abc)

I will get hi as output

I currently have this, but it is completely not working;

def hi_var(var_name):
  text = "hi"
  return text as var_name

It would be great if someone knew how to do this

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • This is not possible in Python, in general. It also isn't really desirable or necessary. – juanpa.arrivillaga Dec 28 '20 at 09:25
  • 2
    So, why not just `abc = hi_var()`? – juanpa.arrivillaga Dec 28 '20 at 09:25
  • 1
    Does this answer your question? [generating variable names on fly in python](https://stackoverflow.com/questions/4010840/generating-variable-names-on-fly-in-python) – rfkortekaas Dec 28 '20 at 09:30
  • 3
    It's not entirely clear what you are trying to do. Do you want ``hi_var(abc)`` to be equivalent to ``abc = "hi"``? What do you expect to happen when ``hi_var`` is used in a class or function scope, or in another expression – which namespace should the variable be set in? Is there any reason why you do not just use the equivalent assignment statement or expression? – MisterMiyagi Dec 28 '20 at 09:52

3 Answers3

0

I am not sure why you want to do this, but if you like you can access the global variable directory and add the variable there:

def hi_var(var_name):
    text = 'hi'
    globals()[var_name] = text

hi_var('abc')
print(abc)
Querenker
  • 2,242
  • 1
  • 18
  • 29
0

@Querenker's solution will work, but generally speaking it's not great to use global variables. It gets a bit messy. Also unit testing can get tricky.

I think it would be better to store everything somewhere specific.

eg:

dynamic_goodies = {}

def hi_var(var_name):
  text = "hi"
  dynamic_goodies[var_name] = text
  return text

hi_var(`abc`)
print(dynamic_goodies['abc'])

If this doesn't solve it for you can you add a little more info to your question? Why do you want to do this thing?

Sheena
  • 15,590
  • 14
  • 75
  • 113
0

In python, module variables which includes the REPL gets stored in a dictionary called globals(). Typing globals() into the console will show the dictionary.

Although, the question being not so clear to me, as far I understood you needed a function that can assign values to variables. So, here's an example of such a function.

def cv(var_name, value='hi'): 
    """
    create varibles
    """
    globals()[var_name] = value

cv('h')
print(h)

Output:

hi
Anaam
  • 124
  • 6
  • 1
    Variables are *not* all stored in the ``globals`` dictionary. Only module variables, which includes the REPL, are stored in ``globals``. Python knows *at least* three other kinds of variables, namely (function) local, closure and class. – MisterMiyagi Dec 28 '20 at 10:33