質問

I'd been used to doing this in pymongo as a means of accessing a particular database:

import pymongo

connection = pymongo.MongoClient()
db = connection.DBNAME

then querying db.collectioname.find(), etc. However, I now want to be able to connect to databases named via variable, with an eye to looping over a series of databases. So something like:

dbname = 'DBNAME'

connection = pymongo.MongoClient()
db = eval('connection.' + dbname)

I have been taught that eval() is occasionally the devil and should be avoided. How can I do this with setattr() or other solution? Something like...

dbname = 'DBNAME'

connection = pymongo.MongoClient()
db = setattr(connection, '??name??', dbname)
役に立ちましたか?

解決

You want getattr, not setattr.

db = getattr(connection,dbname)

where setattr is a way to set an attribute if you know it's name, getattr is a way to get an attribute if you know it's name.

In other words, the following are 100% equivalent:

db = connection.DBNAME
db = getattr(connection,'DBNAME')
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top