How do I distinguish a variable passed as input to a function that's hardcoded, vs a locally defined variable?

76 Views Asked by At

If I have:

def my_func(x: str) -> void:
  //

def my_caller_func()-> void  
  local_var = "xyz"
  local_var_2 = "zzz"
  my_func(x=local_var)

I am trying to write a libcst visitor that will detect that the input value passed into my_func's x input is "xyz"

Is that possible?

1

There are 1 best solutions below

0
On

I think you might find a decorator could do something like what you are looking to do (not knowing anything about libcst). You seem to want to be able to do "something" if the value passed to my_func() is "xyz" potentially without modification to my_funct().

A decorator seems to fit the bill...

def log_if_x_interesting(func):
    def inner(x):
        if x == "xyz":
            print("interesting")
        func(x=x)
    return inner

@log_if_x_interesting
def my_func(x: str):
    print(x)

def my_caller_func():
  local_var = "xyz"
  local_var_2 = "zzz"
  my_func(x=local_var)
  my_func(x=local_var_2)

my_caller_func()

That should give you:

interesting
xyz
zzz

If that would help.