Search code examples
pythonparameters

Print parameter value if it exists for all class methods


I have a class I wrote where a majority (but not all) of its methods take in an int parameter foo:

class MyClass:
    def fun_one(self, foo: int):
        pass

    def fun_two(self, foo: int, flu: int):
        pass

    def fun_three(self, flu: str, foo: int):
        pass

    def fun_four(self):
        pass

Is there any way I can make my program log the values of foo whenever they come in in any of the methods without needing to manually go to every relevant function and add print(foo)?

Also important to note, sometimes None will be passed as a parameter to these functions. There needs to be a distinction between functions which simply don't have the parameter and functions where the parameter's value is None.

The easiest solution I can think of is using regex to find every instance of def … foo … :, then adding a line break and print statement after each line, but I'm trying to see if there's a built-in, nicer way I can do this.

Thank you so much!


Solution

  • You could add this to every method:

    if 'foo' in locals():
        print(foo)