0

I have a function that takes a given variable as an argument. This variable is a numpy array. Example in pseudo-code:

def foo(var):
   if 'test' in the name of var:
      do something

return

I have tried different options, like

if 'test' in var: 

or

if var == 'test_complete_name_of_var'

But these just check the values of the array, and not the variable name. I was hoping there could be some sort of trick such as:

if 'test' in var.name()

Any ideas on how to solve this?

11
  • 4
    Why do you think you need to do this? Commented Aug 3, 2020 at 13:52
  • You can't easily do that. Why not change the function signature to def foo(var, test=False):? Commented Aug 3, 2020 at 13:53
  • 1
    Usually if you want to do something like that you can create a dictionary and store the variable under a name. This way you can also check for it. Commented Aug 3, 2020 at 13:56
  • 1
    related: stackoverflow.com/questions/2749796/… Commented Aug 3, 2020 at 13:57
  • 2
    might also be helpful: stackoverflow.com/questions/18425225/… Commented Aug 3, 2020 at 13:58

2 Answers 2

1

Usually if you want to do something like that you can create a dictionary and store the variable under a name. This way you can also check for it.

Example:

dict_variables = {}
dict_variables["var_1"] = ["a", "b", "test"]

def foo(var_name):
    var_value = dict_variables.get(var_name)
    if 'var_' in var_name:
       print(var_value)
       
foo("var_1")
#out: ['a', 'b', 'test']

Usefull e.g. for path and dataframe variables.

Sign up to request clarification or add additional context in comments.

Comments

0

First, install the varname library

pip install python-varname

then use it as the following example:

from varname import nameof

def foo(var):
    if 'test' in nameof(var):
      ###do something

4 Comments

That sounds like massive overkill. The name is literally hard-coded to var. That's just how the language works
And how would you check if the name contains a certain string?
if 'test' in 'var':
While I think that the library is neat, I have no idea why it is even remotely useful. I can't think of any use-case where knowing the name something is being assigned to leads to robust code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.