[Tutor] Help with vars()

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 10 Aug 2001 02:18:50 -0700 (PDT)


On Fri, 10 Aug 2001, Charlie Clark wrote:

> I'd like to use vars() in together with a database command (Marc Andr=E9=
=20
> Lemburg's mxODBC) but seem to have missed something.
>=20
> articles =3D {'sternzeichen': 'Wassermann', 'text': 'Es wird besser',=20
> 'headline': 'Horoskop f\xc3\xbcr Peter'}
>=20
> when I use
> insert =3D "%headline, %text, %sternzeichen" %vars(articles)

Hi Charlie.  Let's take a look:


###
>>> articles =3D {'sternzeichen': 'Wassermann', 'text': 'Es wird besser',
=2E..             'headline': 'Horoskop f\xc3\xbcr Peter'}
>>> vars(articles)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: vars() argument must have __dict__ attribute
>>> print vars.__doc__
vars([object]) -> dictionary
=20
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
###


I see.  vars() is meant to grab all the variables out of something like a
module, but it appears that we can't do the same on a dictionary.  The
error message is somewhat confusing: the online docs should make it more
clear that not just any old object will do... hmmm.  I'll have to think
about a good reason why it behaves that way.


> I get a TypeError:
> TypeError: vars() argument must have __dict__ attribute
>=20
> but articles is a dictionary... what screamingly obvious thing am I
> missing?


Start screaming.  *grin* We won't need to call vars() at all: we can just
do the interpolation directly with the dictionary that's in our hands:

###
>>> insert =3D "%(headline)s, %(text)s, %(sternzeichen)s" % articles
>>> print insert
Horoskop fr Peter, Es wird besser, Wassermann
###


Note: the string formatting above requires us to put the variables in the
'%(foo)s' sorta format --- the trailing 's' doesn't stand for plurality,
but for 'string'ality.

Hope this helps!