16 response = requests.get(url)
17 return response.json()
18
19 def submit_transaction(self, transaction):20 url = f"{self.base_url}/transactions"
21 headers = {"Content-Type": "application/json"}
22 response = requests.post(url, json=transaction, headers=headers)
19
20 def navigate(self, current_coordinates):
21 X = np.array([current_coordinates]).reshape(1, -1)
22 predicted_coordinates = self.model.predict(X)23 return predicted_coordinates[0]
24
25
17 )
18 self.model.fit(X_train, y_train)
19
20 def navigate(self, current_coordinates):21 X = np.array([current_coordinates]).reshape(1, -1)
22 predicted_coordinates = self.model.predict(X)
23 return predicted_coordinates[0]
4
5
6class AutonomousNavigation:
7 def __init__(self, sensor_data, target_coordinates): 8 self.sensor_data = sensor_data
9 self.target_coordinates = target_coordinates
10 self.model = RandomForestRegressor()
4
5
6class AutonomousNavigation:
7 def __init__(self, sensor_data, target_coordinates): 8 self.sensor_data = sensor_data
9 self.target_coordinates = target_coordinates
10 self.model = RandomForestRegressor()
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()