1

Why is a variable interpreted differently when inserted into a function?

my_variable = ['list_item1','another_list_item']

var_name = [ i for i, a in locals().items() if a == my_variable][0]
print("The variable name is:", var_name)

def print_and_logging(input):
    var_name = [ i for i, a in locals().items() if a == input][0]
    print("The variable name is:", var_name)
print_and_logging(my_variable)


#Output
'''
The variable name is: my_variable
The variable name is: input
'''
Benjamin T
  • 11
  • 2

1 Answers1

1

Let's decompose this.

my_variable is the name by which you refer to an object, specifically an array containing two strings, ['list_item1','another_list_item']

This name exists in the outermost context of your code, the global namespace.

Now, when you are calling the function print_and_logging with the name my_variable as argument, what you are passing to it is not the name, but the object to which the name refers. The object is hence introduced in the context of the function, which forms a local namespace. The name by which the array object is introduced into (and therefore known to) this namespace is input. But that is still the same object.

If you experiment a bit more, you'll find that you can actually use the name my_variable inside your function, but that the name input is unknown outside of the function.

I think you'll find this post informative. Going forward, you might also want to make research on the concept of namespace and look how arguments are passed in python.

ye olde noobe
  • 1,186
  • 6
  • 12