12
13
14@app.route('/set/<pin:int>/<state:int>')
15def set(pin, state):16 if pin not in pins:
17 abort(code=404, text="pin useless")
18 if state not in (1, 0):
27 if state not in (1,0):
28 abort(code=404, text= "invalid state "+str(state))
29 gpio.output(pins, state)
30 for pin in states:31 states[pin] = state
32 return "all pins changed to "+str(state)
33
38
39
40@app.get('/get/<pin:int>')
41def get(pin):42 if pin not in pins:
43 abort(code=404, text="pin useless")
44 return str(states.get(pin))
50
51
52@app.get('/switch/<pin:int>')
53def switch(pin):54 if not pin:
55 abort(code=404, text="pin not provided")
56 if pin not in pins:
The local variable name hides the variable defined in the outer scope, making it inaccessible and might confuse.
filename = 'myfile.txt'
def read_file(filename): # This shadows the global `filename`
with open(filename) as file:
return file.readlines()
FILENAME = 'myfile.txt' # renamed global to UPPER_CASE as convention
def read_file(filename):
with open(filename) as file:
return file.readlines()
Another usual suspect of this is when you use the same parameter name inside a function as the global variable you are using. For example:
def run_app(app):
# This `app` shadows the global app...
app.run()
if __name__ == '__main__':
app = MyApp() # This is a global variable!
run_app(app)
To avoid this re-defining of a global, consider not defining app
as a global, but inside a main()
function instead:
def run_app(app):
# There is no longer a global `app` variable.
app.run()
def main():
app = MyApp()
run_app(app)
if __name__ == '__main__':
main()