python - pymongo why we can use a dot to get a collection instance? -
from pymongo import mongoclient dbc = mongoclient("localhost").test.test
just snippet above, can use .
instead of get_database("test")
, get_collection("test")
database instance or collection instance. despite convenience, wonder makes syntactic sugar happen?
there __getattr__()
magic method making dot notation/attribute lookup happen.
let's source code. mongoclient
class defines __getaattr__
method , instantiates database
class name:
def __getattr__(self, name): """get database name. raises :class:`~pymongo.errors.invalidname` if invalid database name used. :parameters: - `name`: name of database """ if name.startswith('_'): raise attributeerror( "mongoclient has no attribute %r. access %s" " database, use client[%r]." % (name, name, name)) return self.__getitem__(name) def __getitem__(self, name): """get database name. raises :class:`~pymongo.errors.invalidname` if invalid database name used. :parameters: - `name`: name of database """ return database.database(self, name)
Comments
Post a Comment