0

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?

user1008636
  • 2,989
  • 11
  • 31
  • 45
  • not just a `if x == "xyz"` inside `my_func`? – Cornelius-Figgle Mar 15 '23 at 17:18
  • 1
    would a decorator work for you? – JonSG Mar 15 '23 at 17:18
  • 1
    It's not clear what you want to distinguish. As far as the CST is concerned, `my_func` is a function whose `x` parameter is bound to a `str` value; it does not know or care where that value will come from. You seem to be confusing the *parse* tree with the runtime call tree. – chepner Mar 15 '23 at 17:21
  • 3
    And don't write your question in a hybrid of Python and C(++). There is no type `void`, and comments do not start with `//`. – chepner Mar 15 '23 at 17:22
  • In the context of a CST, the *call* to `my_func` is constructed from a keyword argument using a locally defined variable. The call, though, is independent of whatever definition the name `my_func` may have, which is a *semantic* consideration. – chepner Mar 15 '23 at 17:27

1 Answers1

0

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.

JonSG
  • 10,542
  • 2
  • 25
  • 36