Redefining name 'y' from outer scope (line 217)
177 def main():
178 # observations / data
179 x = np.array(data_point_list_x)
180 y = np.array(data_point_list_y)181
182 # estimating coefficients
183 b = estimate_coef(x, y)
Redefining name 'x' from outer scope (line 83)
176
177 def main():
178 # observations / data
179 x = np.array(data_point_list_x)180 y = np.array(data_point_list_y)
181
182 # estimating coefficients
Redefining name 'y' from outer scope (line 217)
155 return (b_0, b_1)
156
157
158 def plot_regression_line(x, y, b):159 # plotting the actual points as scatter plot
160 plt.scatter(x, y, color="m",
161 marker="o", s=30)
Redefining name 'x' from outer scope (line 83)
155 return (b_0, b_1)
156
157
158 def plot_regression_line(x, y, b):159 # plotting the actual points as scatter plot
160 plt.scatter(x, y, color="m",
161 marker="o", s=30)
Redefining name 'y' from outer scope (line 217)
136
137 operatorReaction(x)
138 operatorReaction2(x)
139 def estimate_coef(x, y):140 # number of observations/points
141 n = np.size(x)
142
Redefining name 'x' from outer scope (line 83)
136
137 operatorReaction(x)
138 operatorReaction2(x)
139 def estimate_coef(x, y):140 # number of observations/points
141 n = np.size(x)
142
Redefining name 'x' from outer scope (line 83)
111 print("Enter a valid function try again! ")
112 sys.exit()
113
114 def operatorReaction2(x):115 if function[index] in multiplication:
116 y_value = x * float(function[index+1])
117 ys.append(y_value)
Redefining name 'x' from outer scope (line 83)
99 i=1
100 index = index + 1
101
102 def operatorReaction(x):103 if function[index] in addition:
104 y_value = x + float(function[index+1])
105 ys.append(y_value)
Redefining name 's' from outer scope (line 212)
18class Snake():
19 snake, fruit = None, None
20
21 def __init__(self, s, genome): 22 self.genome = genome
23
24 self.s = s
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()