I'm building a GameClient-Class in Python which handles user input and has to read from a database (MongoDb). I want to know if that is the best practice to implement it, so that I can use it with Python's with
statement.
Because I want to use different functions of my Client
class, __enter__
has to return self
, so that I can use the instance of that class like normal. Is that best practice?
class Client(object):
def __init__(self, playerid):
self.MongoClient = MongoClient()
self.db = self.MongoClient['worldbg-database']
self.id = playerid
def __exit__(self, exception_type, exception_val, trace):
self.MongoClient.close()
def __enter__(self):
return self
def handle_input(self, input):
if input == "exit":
return False
with Client("id") as GameClient:
GameClient.select_my_tile(GameClient.get_my_tiles()[0]['_id'])
while GameClient.handle_input(raw_input('command: ')):
pass