python - Pymongo database object client possesses any attribute? -


i'm going through pymongo tutorial , there's 1 thing don't understand.

we shown can create database collection this:

>>>client = mongoclient()    >>>print(client)  mongoclient(host=['localhost:27017'], document_class=dict, tz_aware=false, connect=true)   >>>db = client.test_database >>>print(db)  database(mongoclient(host=['localhost:27017'], document_class=dict, tz_aware=false, connect=true), 'test_database')  >>>collection = db.test_collection #posts collection. >>>print(collection)  collection(database(mongoclient(host=['localhost:27017'], document_class=dict, tz_aware=false, connect=true), 'test_database'), 'test_collection') 

my initial thought was: "did make sure include test_database attribute client , test_collection attribute database make work tutorial?" further experimentation showed me create databases , collections in way "attribute name" please! example:

>>>client = mongoclient() >>>db = client.foo >>>print(db)  database(mongoclient(host=['localhost:27017'], document_class=dict, tz_aware=false, connect=true), 'foo')  >>>collection = db.bar >>>print(collection)  collection(database(mongoclient(host=['localhost:27017'], document_class=dict, tz_aware=false, connect=true), 'foo'), 'bar') 

how work in python? i've tried understand reading pymongo files in github repository it's quite difficult newbie understand.

mongoclient overrides "magic" method, __getattr__. whenever access attribute on mongoclient object isn't property or attribute of object, example when access "test_database", python interpreter calls:

client.__getattr__("test_database") 

the implementation of mongoclient.__getattr__ creates database object , returns it.

database overrides __getattr__ return collection name.

both classes override __getitem__ bracketed access works:

client["test_database"] 

see __getattr__ docs here.


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -