Redefining name 'y' from outer scope (line 212)
172 def main():
173 # observations / data
174 x = np.array(data_point_list_x)
175 y = np.array(data_point_list_y)176
177 # estimating coefficients
178 b = estimate_coef(x, y)
Redefining name 'x' from outer scope (line 78)
171
172 def main():
173 # observations / data
174 x = np.array(data_point_list_x)175 y = np.array(data_point_list_y)
176
177 # estimating coefficients
Redefining name 'y' from outer scope (line 212)
150 return (b_0, b_1)
151
152
153 def plot_regression_line(x, y, b):154 # plotting the actual points as scatter plot
155 plt.scatter(x, y, color="m",
156 marker="o", s=30)
Redefining name 'x' from outer scope (line 78)
150 return (b_0, b_1)
151
152
153 def plot_regression_line(x, y, b):154 # plotting the actual points as scatter plot
155 plt.scatter(x, y, color="m",
156 marker="o", s=30)
Redefining name 'y' from outer scope (line 212)
131
132 operatorReaction(x)
133 operatorReaction2(x)
134 def estimate_coef(x, y):135 # number of observations/points
136 n = np.size(x)
137
Redefining name 'x' from outer scope (line 78)
131
132 operatorReaction(x)
133 operatorReaction2(x)
134 def estimate_coef(x, y):135 # number of observations/points
136 n = np.size(x)
137
Redefining name 'x' from outer scope (line 78)
106 print("Enter a valid function try again! ")
107 exit()
108
109 def operatorReaction2(x):110 if function[index] in multiplication:
111 y_value = x * float(function[index+1])
112 ys.append(y_value)
Redefining name 'x' from outer scope (line 78)
94 i=1
95 index = index + 1
96
97 def operatorReaction(x): 98 if function[index] in addition:
99 y_value = x + float(function[index+1])
100 ys.append(y_value)
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()