473,386 Members | 1,828 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

**kwds behavior?

Why does the following attempts to pass in keywords arguments not
work. It would be alot cooler if there was a way to not have to have
the function defined with the variable name. It really seems to me
that the 3rd function should work. Does anyone know how to accomplish
something like this.
def testKeywords1 (**kwds):
print x

def testKeywords2 (**kwds):
locals().update(kwds)
print x

def testKeywords3 (**kwds):
locals().update(kwds)
def testNested():
print x
testNested()

dict = {}
dict['x'] = 5
# doesn't work
testKeywords1(**dict)
# doesn't work
testKeywords2(**dict)
# doesn't work
testKeywords3(**dict)
Jul 18 '05 #1
9 2155

The description of the locals() function is:

Update and return a dictionary representing the current local symbol table.
Warning: The contents of this dictionary should not be modified; changes may
not affect the values of local variables used by the interpreter.

Note that this implies that the dictionary is essentially
read only. What you're trying to do shouldn't work.

John Roth

"Paradox" <Jo*****@netzero.com> wrote in message
news:92**************************@posting.google.c om...
Why does the following attempts to pass in keywords arguments not
work. It would be alot cooler if there was a way to not have to have
the function defined with the variable name. It really seems to me
that the 3rd function should work. Does anyone know how to accomplish
something like this.
def testKeywords1 (**kwds):
print x

def testKeywords2 (**kwds):
locals().update(kwds)
print x

def testKeywords3 (**kwds):
locals().update(kwds)
def testNested():
print x
testNested()

dict = {}
dict['x'] = 5
# doesn't work
testKeywords1(**dict)
# doesn't work
testKeywords2(**dict)
# doesn't work
testKeywords3(**dict)

Jul 18 '05 #2
Changes to locals() do not necessarily affect anything.
locals()
Update and return a dictionary representing the current local
symbol table. *Warning*: The contents of this dictionary should
not be modified; changes may not affect the values of local
variables used by the interpreter.
-- http://python.org/doc/current/lib/bu...cs.html#l2h-47

You should probably try a different approach to whatever the underlying
task is.

Jeff

Jul 18 '05 #3

"Paradox" <Jo*****@netzero.com> wrote in message
news:92**************************@posting.google.c om...
Why does the following attempts to pass in keywords arguments not
work.
What do you mean 'not work'. What was your output and what did you
expect?
It would be alot cooler if there was a way to not have to have
the function defined with the variable name.
I don't understand your meaning here.

It really seems to me that the 3rd function should work. Does anyone know how to accomplish something like this.
Again, what is 'this'?
def testKeywords1 (**kwds):
print x
If you want posted code to be read with indents by everybody, use
space instead of tab to indent. It's your choice to limit readership
or not.

def testKeywords2 (**kwds):
locals().update(kwds)
Above line has same effect as 'pass' for reason John Roth quoted.
print x

def testKeywords3 (**kwds):
locals().update(kwds)
def testNested():
print x
testNested()

dict = {}
dict['x'] = 5
# doesn't work
I usually expect 'doesn't work' to apply to the line above that I just
read -- just as this response applies to the line quoted above. I
suspect you meant 'below doesn't work', whatever 'doesn't work means.
The alternative way to reverse the 'pointer' is to leave a space above
and none below.
testKeywords1(**dict)
# doesn't work
testKeywords2(**dict)
# doesn't work
testKeywords3(**dict)


If you don't get your question answered with above, try again with
different words.

Terry J. Reedy
Jul 18 '05 #4

"Sean Ross" <sr***@connectmail.carleton.ca> wrote in message
news:2S******************@news20.bellglobal.com...
better if attempting to write to an non-writable dict raised an exception, but that is not the current behaviour.
The dict returned by locals(), even within a function, *is* writable
def f(): .... l = locals()
.... l[5] = 6
.... print l
.... f()

{5: 6}

However, it is only a dict copy of the local namespace, (which in
CPython happens to not be a dict of any sort).
So, your call to update has no effect
on the local namespace and, thus, 'x' is not yet defined locally.


So d=locals() can be used for what it is -- a dict initialized from
the local namespace at a particular time, but which is thereafter
independent from the local namespace.

Terry J. Reedy
Jul 18 '05 #5
Paradox wrote:
Why does the following attempts to pass in keywords arguments not
work. It would be alot cooler if there was a way to not have to have
the function defined with the variable name. It really seems to me
that the 3rd function should work. Does anyone know how to accomplish
something like this.
"this" apparently means, that you want to create local variables (within in the
function) with the same names as the keyword arguments.
def testKeywords1 (**kwds):
print x

def testKeywords2 (**kwds):
locals().update(kwds)
print x

def testKeywords3 (**kwds):
locals().update(kwds)
def testNested():
print x
testNested()


As people already pointed out, modifying locals() like this doesn't work.
There is a solution, but before using it you should stop and ask yourself why
you want this. Is there a reason why leaving the values in the dict isn't
sufficient? (Or putting them in a special class, like one poster suggested.)
Creating variables on-the-fly is usually a bad idea.

Now, on to the yucky solution:
def g(**kwargs): for key, value in kwargs.items():
exec "%s = %s" % (key, repr(value))
# test test...
print x
d = {}
d['x'] = 5
g(**d)

5

HTH,

--
Hans (ha**@zephyrfalcon.org)
http://zephyrfalcon.org/

Jul 18 '05 #6

"Hans Nowak" <ha**@zephyrfalcon.org> wrote in message
news:ma**********************************@python.o rg...
Now, on to the yucky solution:
>>> def g(**kwargs):

for key, value in kwargs.items():
exec "%s = %s" % (key, repr(value))
# test test...


This is cute but limited. It only works when values ==
eval(repr(value)), which is to say, numbers, strings, and,
recursively, tuples, lists, and dicts and some user-class instances.
Others will raise syntax error.

Terry J. Reedy
Jul 18 '05 #7
On Tue, Sep 02, 2003 at 01:10:41PM -0400, Hans Nowak wrote:
Now, on to the yucky solution:
def g(**kwargs): for key, value in kwargs.items():
exec "%s = %s" % (key, repr(value))
# test test...
print x

[...]
Now, you don't need to do that. This one works:
def testKeywords5(**kwds):
exec ""
locals().update(kwds)
print x
testKeywords5(x=5)

5

even this variant should work (without actually executing any "exec"
statements):
def testKeywords6(**kwds):
locals().update(kwds)
print x
return
exec ""

.... but I don't think you can/should depend that either variation works.
The key is that when the compiler sees 'bare exec' it disables an
optimization used to turn local name accesses into fast C-array-based
indexing operations...

I stand by my words that you (the OP) should back up a step and choose a
solution that doesn't have this yucky requirement of locals that aren't
known at bytecompile time.

Jeff

Jul 18 '05 #8
On 2 Sep 2003 07:52:22 -0700, Jo*****@netzero.com (Paradox) wrote:
Why does the following attempts to pass in keywords arguments not
work. It would be alot cooler if there was a way to not have to have
the function defined with the variable name. It really seems to me
that the 3rd function should work. Does anyone know how to accomplish
something like this.
def testKeywords1 (**kwds):
print x

def testKeywords2 (**kwds):
locals().update(kwds)
print x

def testKeywords3 (**kwds):
locals().update(kwds)
def testNested():
print x
testNested()

dict = {}
dict['x'] = 5
# doesn't work
testKeywords1(**dict)
# doesn't work
testKeywords2(**dict)
# doesn't work
testKeywords3(**dict)


A couple of other things that might relate to what you want:
def testkw(**kw): ... exec 'print x' in kw
... testkw(x='did it work?') did it work?

Guess so, but testkw(y='did it work?') Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in testkw
File "<string>", line 1, in ?
NameError: name 'x' is not defined

Note that that's a NameError, not a KeyError, as in: def testkw1(**kw): ... print '%(x)s' % kw
... testkw1(x='did it work?') did it work?

Ok, but testkw1(y='did it work?') Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in testkw1
KeyError: 'x'

Yet another way ...
def testkw2(**kw): ... ns = type('',(),kw)()
... print ns.x
... testkw2(x='did it work?') did it work?
testkw2(y='did it work?') Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in testkw2
AttributeError: '' object has no attribute 'x'

Or silliness,
def testkw3(**kw): ... exec """
... def foo():
... print x
... """ in kw
... kw['foo']()
... testkw3(x='did it work?') did it work?
testkw3(y='did it work?')

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 6, in testkw3
File "<string>", line 3, in foo
NameError: global name 'x' is not defined

So what are you actually trying to do?

Regards,
Bengt Richter
Jul 18 '05 #9
Thanks for the replies. basically what I was trying to accomplish was
to be able to load a script text file with python syntax into a class
and have it be able to cleanly reference the properties and methods.

I have currently accomplished it with something like this

code = compile(scriptText, '<string>','exec')
exec code in self.__dict__
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
by: E. Robert Tisdale | last post by:
In the context of the comp.lang.c newsgroup, the term "undefined behavior" actually refers to behavior not defined by the ANSI/ISO C 9 standard. Specifically, it is *not* true that "anything can...
23
by: Ken Turkowski | last post by:
The construct (void*)(((long)ptr + 3) & ~3) worked well until now to enforce alignment of the pointer to long boundaries. However, now VC++ warns about it, undoubtedly to help things work on 64...
6
by: mdcb808 | last post by:
I am writing a C extension with python 2.3.5 and need constructs similar to python func(*args, **kwds) What's a neat way to do that? I found pyrex has a __Pyx_GetStarArgs - is there something...
7
by: Mike Livenspargar | last post by:
We have an application converted from v1.1 Framework to v2.0. The executable references a class library which in turn has a web reference. The web reference 'URL Behavior' is set to dynamic. We...
15
by: George Sakkis | last post by:
Although I consider dict(**kwds) as one of the few unfortunate design choices in python since it prevents the future addition of useful keyword arguments (e.g a default value or an orderby...
12
by: Rajesh S R | last post by:
Can anyone tell me what is the difference between undefined behavior and unspecified behavior? Though I've read what is given about them, in ISO standards, I'm still not able to get the...
28
by: v4vijayakumar | last post by:
#include <string> #include <iostream> using namespace std; int main() { string str; str.resize(5); str = 't';
1
by: Luis Zarrabeitia | last post by:
Hi there. I just tried this test: ==== def f(**kwds): print kwds import UserDict d = UserDict.UserDict(hello="world")
33
by: coolguyaroundyou | last post by:
Will the following statement invoke undefined behavior : a^=b,b^=a,a^=b ; given that a and b are of int-type ?? Be cautious, I have not written a^=b^=a^=b ; which, of course, is undefined....
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.