[Tutor] Turning kwargs into scalars

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Nov 1 07:16:56 CET 2005

On Mon, 31 Oct 2005, Steve Bergman wrote:

> Say I have a function:
> def f(self, **kwargs) :
> and I want to take the key/value pairs and create a set of variables
> with the names of the keys.
> For example, if I say:
> f(x=5, y=2)
> I want to create local variables 'x' and 'y' in the function, with
> values of 5 and 2 respectively.

Hi Steve,

It's technically possible to do this in Python, but it's not advised to do
it, just because it becomes difficult to control what local variables will
be created.  That can make debugging very hard.  It also wrecks havoc with
lint-like programs like pychecker: http://pychecker.sourceforge.net/.

I guess I'm trying to say: are you really sure you want to do this?

We can access those values through the kwargs dictionary though; is this
sufficient?  It's a very rare case where we want to really make local
variable names in such a dynamic way; perhaps there's another approach to
the problem you're solving?  If you can show us more of what you're trying
to do, we can give more suggestions.

Best of wishes!

More information about the Tutor mailing list