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

Prevent use of Database and Collection in boolean expressions

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Major - P3
    • Resolution: Fixed
    • None
    • 4.0
    • None
    • None
    • Major Change

    Description

      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:

      Attachments

        Activity

          People

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

            Dates

              Created:
              Updated:
              Resolved: