Redefining name 'pin' from outer scope (line 69)
11
12
13@app.route('/set/<pin:int>/<state:int>')
14def set(pin, state):15 if pin not in pins:
16 abort(code=404, text="pin useless")
17 if not state in (1, 0):
Redefining name 'pin' from outer scope (line 69)
35
36
37@app.get('/get/<pin:int>')
38def get(pin):39 if pin not in pins:
40 abort(code=404, text="pin useless")
41 return str(states.get(pin))
Redefining name 'pin' from outer scope (line 69)
47
48
49@app.get('/switch/<pin:int>')
50def switch(pin):51 if not pin:
52 abort(code=404, text="pin not provided")
53 if pin not in pins:
Redefining name 'pin' from outer scope (line 69)
24@app.get('/setAll/<state:int>')
25def setAll(state):
26 gpio.output(pins, state)
27 for pin in states:28 states[pin] = state
29 return "all pins changed to "+str(state)
30
Description
The local variable name hides the variable defined in the outer scope, making it inaccessible and might confuse.
Bad practice
filename = 'myfile.txt'
def read_file(filename): # This shadows the global `filename`
with open(filename) as file:
return file.readlines()
Preferred:
FILENAME = 'myfile.txt' # renamed global to UPPER_CASE as convention
def read_file(filename):
with open(filename) as file:
return file.readlines()
Bad practice
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)
Preferred:
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()