0

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)
Mittenchops
  • 18,633
  • 33
  • 128
  • 246

1 Answers1

6

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')
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Yep, thank you, that's very helpful. I wasn't sure that I knew that the database name was properly an attribute. When I typed `dir(connection)`, I didn't see it! – Mittenchops Mar 07 '13 at 20:51