jotNewie
jotNewie

Reputation: 496

Check if substring present in variable name - Python

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?

Upvotes: 0

Views: 589

Answers (2)

Andreas
Andreas

Reputation: 9207

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.

Upvotes: 1

Hussein Fawzy
Hussein Fawzy

Reputation: 366

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

Upvotes: 0

Related Questions