Turning string into object (name)

Chris Angelico rosuav at gmail.com
Fri Jun 26 00:00:07 EDT 2015


On Fri, Jun 26, 2015 at 12:51 PM,  <liam.oshea at o2-v2.com> wrote:
> def dbconn():
>         #Establishes connection to local db
>         try:
>                 conn = client()
>                 db = conn.db_solar #dbname
>                 collection = db.main # dbcollection / Table
>                 print "Connected to database successfully!!!"
>                 return(db,collection)
>         except errors.ConnectionFailure, e:
>                 print "Could not connect to MongoDB: %s" % e
>                 sys.exit()
>
> Now I want to remove the hardcoded 'db_solar' and 'main' (from db.main) and load these values from a config file.
>
> Once I have loaded in a string 'db_solar' from a config file how do I use it such that something like db=conn.db_solar will be constructed and run as expected.
> Thanks

You can retrieve attributes using strings like this:

# Same effect:
db = conn.db_solar
db = getattr(conn, "db_solar")

So a variable attribute name can be handled the same way:

db = getattr(conn, dbname)
collection = getattr(db, dbcollection)

Incidentally, I would suggest not having the try/except at all, since
all it does is print an error and terminate (which is the same result
you'd get if that error bubbled all the way to top level). But if you
are going to use it, then I strongly recommend using the newer syntax:

except errors.ConnectionFailure as e:

unless you have some reason for supporting ancient versions of Python.
For most modern code, you can usually rely on at least 2.7, so the new
syntax works; it's unambiguous in the face of multiple-exception
handlers, and it works identically on Python 3 (the "except type,
name:" syntax isn't supported on Py3). Since it's a trivial syntactic
change, there's generally no reason to use the old form, unless you
actually need your code to run on Python 2.5.

But for what you're doing, chances are you can just let the exception
bubble up. That way, a calling function gets the choice of handling it
some other way, which currently isn't an option.

ChrisA



More information about the Python-list mailing list