My code keeps giving me the above syntax warning. My code includes, but is not limited to:
class SocketHandler(WebSocketHandler): def on_message(self, message): ball = json.loads(message) user = User(ball['identifier']) if ball['command'] == 'search': global our_mongo search_results = our_mongo.find({'$text':{'$search':ball['search_term']}},{'score':{'$meta':"textScore"}}) self.write_message({ 'command': 'search-results', 'results': list(search_results.sort([('score', {'$meta': 'textScore'})]).limit(10)), }) elif ball['command'] == 'save-node': # hopefully this can handle both new nodes and changes to nodes node_dict = ball['node_dict'] if 'importance' in node_dict.keys(): node_dict['importance'] = int(node_dict['importance']) try: node_obj = node.create_appropriate_node(node_dict) print('node made. looks like: '+str(node_obj)+'. Now time to put it into the DB...') global our_mongo # take a look at the dependencies now previous_dependency_ids = [node.reduce_string(dependency) for dependency in list(our_mongo.find({"_id": node_obj.id}))[0]["_dependencies"]] # if this works, try using set() instead of list and elimination the set()s below print('prev deps are: '+str(previous_dependency_ids)) our_mongo.upsert({ "_id": node_obj.id }, node_obj.__dict__) # take a look at the current dependencies current_dependency_ids = [node.reduce_string(dependency) for dependency in list(our_mongo.find({"_id": node_obj.id}))[0]["_dependencies"]] # if this works, try using set() instead of list and elimination the set()s below print('curr deps are: '+str(current_dependency_ids)) update_our_DAG() # send an update of the graph to the user if there is a new dependency: for new_dependency in set(current_dependency_ids) - set(previous_dependency_ids): self.request_node(new_dependency, ball, user) # OR IF THE SAVED NODE IS A BRAND NEW NODE, we have to include all the deps except Exception as error: # stuff didn't work, send error back to user print('ERROR: '+str(error)) self.write_message({ 'command': 'display-error', 'message': str(error), }) def update_our_DAG(): # 1. grab nodes and edges from database all_node_dicts = list(Mongo("math", "nodes").find()) # 2. create a networkx graph with the info... global our_DAG our_DAG = nx.DAG() for node_dict in all_node_dicts: node = create_appropriate_node(strip_underscores(node_dict)) our_DAG.add_n(node) def make_app(): return Application( [ url('/', RedirectHandler, {"url": "index.html"}, name="rooth"), url('/websocket', SocketHandler), url('/json', JSONHandler, name="jsonh"), url(r'/index(?:.html)?', IndexHandler, name="indexh"), # captures anything at all, and serves it as a static file. simple! url(r'/(.*)', StaticHandler, {"path": "../www/"}), ], # settings: debug=True, ) def make_app_and_start_listening(): # enable_pretty_logging() application = make_app() # by listening on the http port (default for all browsers that i know of), # user will not have to type "http://" or ":80" in the URL application.listen(80) # other stuff IOLoop.current().start() if __name__ == "__main__": # 0. create a global mongo object for later use (for upserts in the future) our_mongo = Mongo("math", "nodes") # 1 and 2 update_our_DAG() axioms = [our_DAG.n(node_id) for node_id in ['set', 'multiset', 'vertex']] # 3. launch! make_app_and_start_listening()
I’ve tried everything and it’s still an issue. WHY is this a syntax error? What is the best way to fix this?
Advertisement
Answer
It is not a SyntaxError
but a SyntaxWarning
. Python warns that you’re using our_mongo
variable before a global our_mongo
within the function.
Syntactically it does not actually matter on which line of the function the global
statement is; but the idiomatic way would be to use global
before the first access.
Another issue altogether is that you have multiple global our_mongo
statements, where single would do, and also that you do not even need the global
at all – it is only for the case when you want to assign a new value to the global variable; i.e.
def foo(): global bar # this line is required for the next line # to change the global variable instead of # the local variable bar = 42
Thus, just remove all global
statements altogether from your on_message
, they’re unnecessary.