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):

    def __enter__(self):
        return self

    def handle_input(self, input):
    if input == "exit":
        return False

with Client("id") as GameClient:
    while GameClient.handle_input(raw_input('command: ')):

The reason to use a with clause is 1) clarity and 2) exception handling. Clarity because you have explicitly called out "right here, I am working with the object" and exception handling because you are guaranteed to have the exit handler called and any cleanup accomplished.

Canonical examples are:

with open(filename, "w") as fp:
    data = generate_some_data()
    data2 = more_generation()

with lock:
    # all code in here is locked

You don't provide a lot of information about what you intend to accomplish in the with clause in your code. Typically the with block is not too long and focused on a task. If Client is meant to represent a player then you are probably putting the abstraction in the wrong place. A GameClient class could contain a DBConnection object. This way you could mock out the DB for testing for instance. Or switch to another DB type. If you meant Client to be DBClient I would rename it.

  • \$\begingroup\$ I've edited my question to provide more information \$\endgroup\$ – Eknoes Jul 15 '14 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.