473,651 Members | 2,659 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Checking for invalid keyword arguments?

I've got a function that takes a couple of optional keyword arguments.
I want to check to make sure I didn't get passed an argument I didn't
expect. Right now I'm doing:

conversion = None
drop = False
for key, value in kwArgs.items():
if key == 'conversion':
conversion = value
elif key == 'drop':
drop = value
else:
raise TypeError ('Unexpected keyword argument %s' % key)

which seems kind of verbose. Is there a neater way to do this check?
Jul 18 '05 #1
6 4611
Roy Smith wrote:
I've got a function that takes a couple of optional keyword arguments.
I want to check to make sure I didn't get passed an argument I didn't
expect. Right now I'm doing:

conversion = None
drop = False
for key, value in kwArgs.items():
if key == 'conversion':
conversion = value
elif key == 'drop':
drop = value
else:
raise TypeError ('Unexpected keyword argument %s' % key)

which seems kind of verbose. Is there a neater way to do this check?


Sure, particularly in Python 2.3:

conversion = kwArgs.pop('con version', None)
drop = kwArgs.pop('dro p', False)
if kwArgs:
raise TypeError("Unex pected keyword args: %s" % kwArgs.keys())

The .pop method of dictionary objects, new in 2.3, removes a key from
a dict (if present), returning the corresponding value (or a supplied
default -- if key is absent and no default supplied, it raises). So,
if anything is still left in kwArgs after the two pops, we know there
were "unknown and ignored" keyword arguments in dict kwArgs.

Of course, in most cases you'd simply declare your function with:

<funcname>(<wha tever other args>, conversion=None , drop=False):

and no **kwArgs, and just let Python do the checking for you. But
when the kwArgs DO have to come in a dict (as, rarely, does happen,
for a variety of peculiar reasons), the new 2.3 idiom will help.
Alex

Jul 18 '05 #2
Roy Smith wrote:

I've got a function that takes a couple of optional keyword arguments.
I want to check to make sure I didn't get passed an argument I didn't
expect. Right now I'm doing:

conversion = None
drop = False
for key, value in kwArgs.items():
if key == 'conversion':
conversion = value
elif key == 'drop':
drop = value
else:
raise TypeError ('Unexpected keyword argument %s' % key)

which seems kind of verbose. Is there a neater way to do this check?


I'd suggest writing a general-purpose subroutine which can do the necessary
checks for you, then use a one-liner to call it with the "pattern" you
require. It might look like this for the call:

conversion, drop = checkOptArgs(kw Args, conversion=None , drop=False)

This clearly shows the allowed keyword args, their default values, and assigns
values to the local names on return. It can of course raise the TypeError
for you if a bad name is in kwArgs.

-Peter
Jul 18 '05 #3
On Sun, Sep 28, 2003 at 05:06:11PM -0400, Roy Smith wrote:
I've got a function that takes a couple of optional keyword arguments.
I want to check to make sure I didn't get passed an argument I didn't
expect. Right now I'm doing:

conversion = None
drop = False
for key, value in kwArgs.items():
if key == 'conversion':
conversion = value
elif key == 'drop':
drop = value
else:
raise TypeError ('Unexpected keyword argument %s' % key)

which seems kind of verbose. Is there a neater way to do this check?


Python's built-in default argument mechanism does exactly that:

def f(conversion=No ne, drop=False, ...):
...

I assume that you have some good reason for using kwargs instead such as
passing a bunch of arguments together as a dict but you can unpack this
bunch by calling another function:

def f(**kwargs):
def f2(conversion=N one, drop=False):
...

return f2(**kwargs)

Oren

Jul 18 '05 #4
Roy Smith wrote:

I've got a function that takes a couple of optional keyword arguments.
I want to check to make sure I didn't get passed an argument I didn't
expect.


By the way, you didn't explain why you don't want to get passed arguments
you didn't expect. Can't you simply ignore them? That way you can
easily expand the API in future versions yet maintain a certain amount
of compatibility.

-Peter
Jul 18 '05 #5
Peter Hansen <pe***@engcorp. com> wrote:
By the way, you didn't explain why you don't want to get passed arguments
you didn't expect. Can't you simply ignore them?


I'm taking some early prototype code and changing the API around a bit
as the design evolved. I thought I had changed everything, but had a
bug due to having missed a change in one place. I was calling a routine
using the old API and the now incorrect argument was just being silently
ignored.

Upon further consideration (i.e. having several people point out the
obvious to me!), I've come to realize that I don't really need the
kwArgs mechanism at all. The simplier default mechanism does exactly
what I want! Not clear what got me thinking I needed something more
complicated in the first place.

Thanks for the help.
Jul 18 '05 #6
Roy Smith <ro*@panix.co m> wrote in message news:<ro******* *************** *@reader2.panix .com>...
I've got a function that takes a couple of optional keyword arguments.
I want to check to make sure I didn't get passed an argument I didn't
expect. Right now I'm doing:

conversion = None
drop = False
for key, value in kwArgs.items():
if key == 'conversion':
conversion = value
elif key == 'drop':
drop = value
else:
raise TypeError ('Unexpected keyword argument %s' % key)

which seems kind of verbose. Is there a neater way to do this check?


One solution - which reminds me of *slots* -
could be the following:
def fn(**kwa): .... allowed='conver sion drop some_thing else'.split()
.... not_used =filter(lambda var:var not in kwa,allowed)
.... not_allowed=fil ter(lambda var:var not in allowed,kwa)
.... print 'not_allowed:\t '+'\n\t\t'.join (not_allowed)
.... print 'not_used :\t'+'\n\t\t'.j oin(not_used)
.... fn(drop=1,conve rsion=True,foo= 5, false=False) not_allowed: false
foo
not_used : some_thing
else


Regards
Peter
Jul 18 '05 #7

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

Similar topics

14
5246
by: Edward Diener | last post by:
In the tutorial on functions there are sections on default arguments and keyword arguments, yet I don't see the syntactic difference between them. For default arguments the tutorial shows: def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while for keyword arguments the tutorial shows: def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
2
1539
by: Fuzzyman | last post by:
Sorry if this is a duplicate - I use the google interface and sometiems it screws up (not showing stuff you've posted *or* not posting it). Before you ask it's because at work I have no NNTP and *heavily* restricted http. A colleague and I have built a Validator object for use with ConfigObj and other general schema situations. A config file is used to store a schema that specifies how to test a value that it is valid. ...
20
7077
by: talin at acm dot org | last post by:
Although I realize the perils of even suggesting polluting the Python namespace with a new keyword, I often think that it would be useful to consider defining an operator for testing whether or not an item is a member of a category. Currently, we have the 'in' operator, which tests for membership within a container, and that works very well -- in particular, it allows such membership tests to be expressed in very natural way. So for...
30
2231
by: Michael B Allen | last post by:
I have a general purpose library that has a lot of checks for bad input parameters like: void * linkedlist_get(struct linkedlist *l, unsigned int idx) { if (l == NULL) { errno = EINVAL; return NULL; }
10
1988
by: Fredrik Tolf | last post by:
If I have a variable which points to a function, can I check if certain argument list matches what the function wants before or when calling it? Currently, I'm trying to catch a TypeError when calling the function (since that is what is raised when trying to call it with an illegal list), but that has the rather undesirable side effect of also catching any TypeErrors raised inside the function. Is there a way to avoid that? Fredrik Tolf
4
2374
by: Patient Guy | last post by:
Does anyone have any coding rules they follow when doing argument checking? When arguments fail during check, do you return from the call with an ambiguous return value, or do you throw exceptions?
10
5114
by: Armando Serrano Lombillo | last post by:
Why does Python give an error when I try to do this: Traceback (most recent call last): File "<pyshell#40>", line 1, in <module> len(object=) TypeError: len() takes no keyword arguments but not when I use a "normal" function: return len(object)
3
4244
by: Sean DiZazzo | last post by:
Why is the following not working? Is there any way to get keyword arguments working with exposed XMLRPC functions? ~~~~~~~~~~~~~~~~ server.py import SocketServer from SimpleXMLRPCServer import SimpleXMLRPCServer,SimpleXMLRPCRequestHandler # Threaded mix-in class
4
5074
by: barmatt80 | last post by:
I am stumped on the error reporting with sql server. I was told i need to return @SQLCode(code showing if successful or not) and @ErrMsg(and the message returned). I am clueless on this. I wrote this procedure: ALTER PROCEDURE . @Emp_SSN int, @Annual_Forward decimal(10,2),
0
8347
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
8792
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
8694
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
8457
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
8571
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6157
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
4280
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2696
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1585
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.