furlat / OpenBugger

Code to create bugged python scripts for OpenAssistant Training, maintained by https://twitter.com/Cyndesama
Apache License 2.0
21 stars 5 forks source link

Bug type: global variables #5

Open mashdragon opened 1 year ago

mashdragon commented 1 year ago

A bug type I've come across myself has been with forgetting to use the global keyword with global variables. Here's an example:

# A globally accessible list
current_labels = []

def reset_current_labels():
    """ Clears the label list """
    current_labels = []

The bug is that calling reset_current_labels() will not modify current_labels:

>>> current_labels.append('delete me')
>>> current_labels
['delete me']
>>> reset_current_labels()
>>> current_labels
['delete me']

The correct code would be

# A globally accessible list
current_labels = []

def reset_current_labels():
    """ Clears the label list """
    global current_labels
    current_labels = []

So to bug the code, you would remove one or more global statements.

furlat commented 1 year ago

Thanks for the suggestion, would this script satisfy your example ? (some of the bugs are unchecked and might not work ) https://github.com/furlat/OpenBugger/blob/3b0a6e597983faac5f13fbae84a68c1ef78c86ef/logic/logic_injector.py#L401

mashdragon commented 1 year ago

Almost. I think to reproduce the bug, the entire global declaration should be missing.