Search code examples
pythonvalueerrorraiserror

Accessing the name of a variable/argument


I'm writing a function in Python to compute some stuff, and if the argument to my function is not of the right type, it fails miserably. So I want to raise an error when that happens.

def do_stuff(x):
    if not isinstance(x, int):
        raise ValueError(f'Argument {x} is not int')
    pass

However, the content of the x is printed, not the name of x, which is useful for debugging purposes. In the real case, x needs to be a pandas.Series but sometimes is applied to a pandas.DataFrame. Printing the content of a DataFrame is completely useless for error tracking.

I'm doing something more like this, and tracking the error with the line number. But having the variable name would be awesome

raise ValueError('Argument to do_stuff(x) is not int')

If it's too ugly or convoluted (like looping over all the variables and compare types and values to get a name that match), then I'll give up.

Thanks

P.S.: I'm using Python 3.9, so the f-string syntax is valid. Not sure if there's any other recent version magic that I could use.


Solution

  • Objects don't have dedicated names in Python. In fact, they can be referenced by multiple names. The best you can do in your example is report the function's argument name because that would at least be unique in the scope of the function. If you don't want to print the object's values, you could just print its type, and it appears that's what you really want to catch:

    def do_stuff(x):
        if not isinstance(x, int):
            raise TypeError(f'Argument x of dostuff(x) is a {type(x)}, should be a {int}')
        pass
    

    PS The __name__ attribute is used to store definition names for classes and functions, but the variables might not always exist (x = do_stuff; del do_stuff; print(x.__name__)).