Uploaded image for project: 'Python Driver'
  1. Python Driver
  2. PYTHON-808

Prevent use of Database and Collection in boolean expressions

    • Type: Icon: Improvement Improvement
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 4.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None
    • Major Change

      Any undefined attribute access on MongoClient gives you a Database, and Python always considers a Database "true":

      if client.pirmary:  # Oops.
          print("I'm connected!")
      

      Database and Collection act this way too, leading to mistakes like the one we corrected here:

      https://github.com/mongodb/mongo-python-driver/commit/73edd2c134f43d58531e3dc26499b777354fb7ea

      Override __nonzero__ and __bool__ for Database and Collection to raise NotImplementedError, preventing accidental use of these objects as bools in Python 2 and 3, respectively.

      This is a breaking change for code like this:

      db = None
      if some_test():
          db = get_a_database()
      
      if db:
          print("We got a Database")
      

      It would need to be rewritten:

      if db is not None:
      

            Assignee:
            julius.park@mongodb.com Julius Park (Inactive)
            Reporter:
            jesse@mongodb.com A. Jesse Jiryu Davis
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: