[Python] How to allow a function argument to accept either a single object or a list of...

Discussão em 'Python' iniciado por Stack, Junho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I am currently designing a set of methods to handle stock market data and would like to create a method that gathers price for different assets, however the choice remains to the call the method with one or multiple tickers, in other words what I need to do is:

    def getPrice(tickers):
    pass


    then call it like this

    getPrice("AAPL")


    or like this

    tickers = ["AAPL", "MSFT", "TSLA"]
    getPrice(tickers)


    I asked Gemini and it recommended the following approach:

    def process_data(data):
    if not isinstance(data, list):
    data = [data] # Convert single element to a list


    This surprised me because I thought there might be a more Pythonic way to do this, considering Python's many built-in conveniences. However, I couldn't find a cleaner or more idiomatic solution.

    Knowing the answers provided at Handle either a list or single integer as an argument are really close to what Gemini gave me and does not seem Pythonic enough to me as I would like to know if there is an inline solution to pass a list of strings or a single string in the arguments of the method.

    Continue reading...

Compartilhe esta Página