'python constantly updating a global variable in a thread

i'm using this library to handle a PN5180 rfid reader:

https://github.com/fservida/pyPN5180

for what i understand in consist in one function named inventory() that return a list of up to 16 detected cards. you put it in a loop in order for it to update

i'd like to be able to test how many cards are in the list at various times as well as returning some ids

so i've tried putting the looped function into to a thread but i don't know ho to update it as a global variable in order to do my tests in the main program.

def ListeningCards():

    print("listening to card thread started")
    while True:
        global cards    
        cards = PN5180().inventory()
        cardcount = len(cards)

th1 = threading.Thread(target = ListeningCards)

th1.start()


#main progam:

while true
#etc

so how can i achieve constant listening of the rfid chip and returning it in my main programme? i tried multithreading but maybe there's other ways?



Solution 1:[1]

cards is undefined until the first time the loop of ListeningCards is run. It may take a few milliseconds for the program to start running. If your main program accesses cards before ListeningCards has had a chance to set it the first time, then you will get an undefined variable.

You might just want to set cards = 0 at the top of your program, or something like that, so that it has a default value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank Yellin