473,804 Members | 2,109 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

**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 2177

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*****@netzer o.com> wrote in message
news:92******** *************** ***@posting.goo gle.com...
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*****@netzer o.com> wrote in message
news:92******** *************** ***@posting.goo gle.com...
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***@connectm ail.carleton.ca > wrote in message
news:2S******** **********@news 20.bellglobal.c om...
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**@zephyrfal con.org)
http://zephyrfalcon.org/

Jul 18 '05 #6

"Hans Nowak" <ha**@zephyrfal con.org> wrote in message
news:ma******** *************** ***********@pyt hon.org...
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(scriptT ext, '<string>','exe c')
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
2599
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 happen" if your C code invokes "undefined behavior". Behavior not defined by the ANSI/ISO C 9 standard may be defined by some other standard (i.e. POSIX) or it may be defined by your compiler, your operating system or your machine architecture.
23
3220
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 bit machines, i.e. with 64 bit pointers. In the early days of C, where there were problems with the size of int being 16 or 32 bits, the response was that an int was guaranteed to hold a pointer (yes, there were 64Kb address spaces at one time!)....
6
1579
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 I'm missing from the regular C/API maybe using one of the PyArg_Parse.. calls ? Thanks, M.
7
22499
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 added an entry to the executable's .exe.config file to specify the URL, and under the 1.1 framework this worked well. Unfortunately, this is not working under the 2.0 framework. I see in the Reference.cs file under the web service reference the...
15
2460
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 function), I've been finding myself lately using it sometimes instead of dict literals, for no particular reason. Is there any coding style consensus on when should dict literals be preferred over dict(**kwds) and vice versa ? George
12
3080
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 difference. For example: Consider the following code: a = i; We say that the above expression statement produces undefined
28
2580
by: v4vijayakumar | last post by:
#include <string> #include <iostream> using namespace std; int main() { string str; str.resize(5); str = 't';
1
3019
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
2849
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. I am having some confusion with the former statement! Also, state the reason for the statement being undefined!
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10604
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10354
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10359
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9177
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7643
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6870
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3837
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.