-1

So, I was wondering if creating a function with variables that are changing names (but only partially) is possible. Here is an example:

def function(string):
    {string} + something = 1
    return {string} + something

So when I call it like:

function(test)

it returns variable called "testsomething" that equals 1.

Hope my question is understandable, is this even possible?

  • 1
    No, it's not. Why do you want to do something like this though? Maybe I could be helpful there. – puppydog May 05 '20 at 15:21
  • 2
    Even if that worked, your function would be exactly equivalent to `return 1`. The fact that the returned value was briefly held in a variable of a certain name is not a detail that's visible outside of the function. – jasonharper May 05 '20 at 15:23
  • I suspect that this is an [XY problem](https://en.wikipedia.org/wiki/XY_problem). How would the name of a local variable matter? What is your interface such that the caller has any interest in this naming? Somewhere, you're violating a basic principle of modularization. – Prune May 05 '20 at 15:29
  • @puppydog Actually I have few almost similar functions (only the variable names differ) which I run in a loop. All of them all yielding variables, and I need to identify them afterwards. – Wiktor Kisielewski May 05 '20 at 15:33
  • @Prune Actually I have few almost similar functions (only the variable names differ) which I run in a loop. All of them all yielding variables, and I need to identify them afterwards. – Wiktor Kisielewski May 05 '20 at 15:34
  • 1
    Ah. Then use @John Gordon's solution. You're looking for a dictionary. – puppydog May 05 '20 at 15:35
  • In that case, this is a straightforward duplicate of [this](https://stackoverflow.com/questions/51887012/how-to-declare-many-variables) – Prune May 05 '20 at 15:38
  • Another solution that my help is exec, see [here](https://stackoverflow.com/questions/19122345/convert-string-to-variable-name-in-python). – jayveesea May 05 '20 at 15:42

1 Answers1

2

It is possible, if you put the variable inside a dictionary:

def function(name):
    mydict = {}
    mydict[name+"something"] = 1
    return mydict
John Gordon
  • 29,573
  • 7
  • 33
  • 58