Search code examples
pythonsetattr

How to use setattr if value is not single?


I want to use setattr to create a plot:

    import numpy as np
    import matplotlib.pyplot as plt

    x = np.random.rand(10)
    y = np.random.rand(10)

    # I want this:
    # plt.scatter(x, y)
    setattr(plt, "scatter", [HOW TO PASS X AND Y])

Since value I want to pass is not single, how should I do it? Basically, this should be the result: plt.scatter(x, y)


Solution

  • I think what you are looking for is getattr. In this case, it will return a Callable, so you can just treat it like a function, like this:

    getattr(plt, 'scatter')(x, y)
    

    Is the same as this:

    plt.scatter(x, y)
    

    Using setattr in that way would be more akin to plt.scatter = (x, y), which I don't think is what you want to do.