Home > Back-end >  How to test all Object values in a python function
How to test all Object values in a python function

Time:01-30

I would like to test all x values in this function, without calling each x value ( x[0] ...), so a kind of x[n] or ' for all values of x'. And to list all TickerZ values in a list depending on if the x value passed the IF statement.

        room = str('Bingo Bango Bungo EURUSD=X')

        x = room.split()
        def Symbol(symbol):
            aapl = yf.Ticker(symbol)
            ainfo = aapl.history(period='1y')
            if len(ainfo) >= 40:
                print('yes it is a symbol')
                global tickerZ
                tickerZ = symbol
                new_Memory = Memory.objects.create(user=current_user, raw_message=room, date1=datemin, date2=datemax, ticker=tickerZ, command=cmd_exec)
                new_Memory.save()
                return tickerZ
                
        symb1 = Symbol(x[0])
        symb2 = Symbol(x[1])
        symb3 = Symbol(x[2])
        symb4 = Symbol(x[3])

Code explanation: So basically, i have a string, i'm splitting it into words, which represent all x values. In this case x[0] is Bingo. I'm passing all x's into a IF statement to filter the relevant x values. I know if a x is relevant if TickerZ has a value, because the variable is defined after the filter.

CodePudding user response:

You could use a list comprehension to iterate over all x values and only add the symbols that pass the Symbol function's if statement to ticker_list. The ticker_list is then used to create and save the new_Memory object

room = str('Bingo Bango Bungo EURUSD=X')

x = room.split()
def Symbol(symbol):
    aapl = yf.Ticker(symbol)
    ainfo = aapl.history(period='1y')
    if len(ainfo) >= 40:
        print('yes it is a symbol')
        global tickerZ
        tickerZ = symbol
        return True
    return False

ticker_list = [symbol for symbol in x if Symbol(symbol)]
new_Memory = Memory.objects.create(user=current_user, raw_message=room, date1=datemin, date2=datemax, ticker=ticker_list, command=cmd_exec)
new_Memory.save()

CodePudding user response:

You could use python's list-comprehension with a generator to solve this with a one-liner:

symbols = [symbol for symbol in (Symbol(y) for y in x) if not symbol is None]

or, alternatively with filter, which may be more readable:

symbols = filter(None, (Symbol(symbol) for symbol in x))

CodePudding user response:

Use a map:

all_tickerz = list(map(Symbol, x))
  • Related