def divide(num1,num2):
try:
return num1/num2
except TypeError:
return "Please provide two integers or floats"
except ZeroDivisionError:
return "Please do not divide by zero"
If you don't supply all of the required arguments, the function is never entered, so there's no way to catch that TypeError from inside the function.
To illustrate, consider a function that immediately errors out:
>>> def func(a, b, c):
... raise Exception("inside the function")
...
Now let's call it with the required arguments:
>>> func(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func
Exception: inside the function
Here you can see from the traceback (in func) that the function was entered and the error thrown from there. However, if we call it again without the arguments:
>>> func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes exactly 3 arguments (0 given)
Note that the traceback doesn't include in func, the error happens before entering the function body. You can only catch it outside the function:
>>> try:
... func()
... except TypeError:
... print('oh no!')
...
oh no!
For positional parameters, you have to pass the same number of arguments. You can use the default argument concept, like :
def divide(num1=1,num2=1):
try:
return num1/num2
except TypeError:
return "Please provide two integers or floats"
except ZeroDivisionError:
return "Please do not divide by zero"
You can call this function using 0,1 or 2 arguments.
Because your try/except statement is catching that exception and returning the designated message.
Try something like this:
try:
if num1 and num2:
return num1 / num2
else:
return "Please provide two numbers"
except ZeroDivisionError:
return "Please do not divide by zero"
except TypeError:
return "Please provide two integers or floats"
I read a solution in the Python Cookbooks for creating a function that only allows name arguments. I wrote my own code to try it out:
class Reporter(object):
def __init__(self, *, testline=None, sw_ver= None, directory=None):
pass
if __name__ == "__main__"
r = Reporter()
However the interpreter shows this error:
File "Reporter.py", line 6
def __init__(self, *, testline=None, sw_ver= None, directory=None):
^
SyntaxError: invalid syntax
Why is it showing this?
The code you are using is valid syntax but for python3 so the book must be using python3 syntax, it allows keyword arguments only, pep-3102:
python 3 new syntax
You can also use a bare * in the parameter list to indicate that you don’t accept a variable-length argument list, but you do have keyword-only arguments.
Using your code and passing a non keyword in python 3 would error but for a different reason:
TypeError Traceback (most recent call last)
<ipython-input-2-b4df44fa1e0c> in <module>()
1 if __name__ == "__main__":
----> 2 r = Reporter(4)
3
TypeError: __init__() takes 1 positional argument but 2 were given
Once you use a keyword it works fine:
In [4]: if __name__ == "__main__":
r = Reporter(testline=4)
...:
Using a function with the same syntax would maybe give a more obvious error:
def f(*, foo=None, bar=None):
return foo, bar
In [6]: f(4)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-a122d87dbe99> in <module>()
----> 1 f(4)
TypeError: f() takes 0 positional arguments but 1 was given
Is is also useful if you want to allow some positional args and have optional keywords args passed but only by name:
def f(a,b, *, foo=None, bar=None):
return a, b, foo, bar
Then passing 3 positional args will error:
In [8]: f(1,2,3)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-b61741968103> in <module>()
----> 1 f(1,2,3)
TypeError: f() takes 2 positional arguments but 3 were given
I received a recent comment about this answer.
→ Please note it targets python2, since OP explicitly tagged his question with python2.7. For python3, see Padraic Cunningham's answer.
[original answer]
You may not use the * alone. In the function declaration, it means "unpack any other unnamed argument in this variable", so you have to give it a variable name.
You can achieve what you want by giving it a name, then checking it is empty, like this:
class Reporter(object):
def __init__(self, *args):
assert not args, "Reporter.__ini__ only accepts named arguments"
Then you'd want to add arguments you can allow, like this:
# won't work
def __init__(self, *args, testline=None, sw_ver= None, directory=None):
...except *args needs to be at the end. But if you put them at the end, you'll see that you can still pass the other arguments unnamed first.
You have to reverse the logic, and take only kwargs.
class Reporter(object):
def __init__(self, **kwargs):
testline = kwargs.pop('testline', None)
sw_ver = kwargs.pop('sw_ver', None)
directory = kwargs.pop('directory', None)
assert not kwargs, 'Unknown arguments: %r' % kwargs
Now, if someone tries to give unnamed argments, they will be rejected.
The star operator (*) is used for unpacking. You can't use it as an argument.
You may want to read Variable-Length Argument Tuples:
Functions can take a variable number of arguments. A parameter name
that begins with * gathers arguments into a tuple. For example,
printall takes any number of arguments and prints them:
def printall(*args):
print args
The gather parameter can have any name you like, but args is
conventional. Here’s how the function works:
>>> printall(1, 2.0, '3') (1, 2.0, '3')
These are a few utility decorators I wrote on a tangent for a Python 2 project I was working on. The exceptions raised mirror, as closely as possible, the ones raised by functions in Python 3 that use the keyword-only arguments syntax.
They don't disallow positional arguments, but they can require/restrict keyword arguments. You could create another decorator that disallowed positional arguments.
import functools
def original_wrapped_function(f):
try:
while True:
f = f.__wrapped__
except AttributeError:
return f
def restrict_kwargs(*allowed_keywords):
def restrict_kwargs_decorator(func):
#functools.wraps(original_wrapped_function(func))
def restrict_wrapper(*args, **kwargs):
for keyword in kwargs:
if keyword not in allowed_keywords:
msg = "%s() got an unexpected keyword argument '%s'"
raise TypeError(msg % (func.__name__, keyword))
return func(*args, **kwargs)
restrict_wrapper.__wrapped__ = func
return restrict_wrapper
return restrict_kwargs_decorator
def require_kwargs(*required_keywords):
def require_kwargs_decorator(func):
#functools.wraps(original_wrapped_function(func))
def require_wrapper(*args, **kwargs):
missing_keywords = []
for keyword in required_keywords:
if keyword not in kwargs:
missing_keywords.append(keyword)
if missing_keywords:
func_name = func.__name__
count = len(missing_keywords)
if count == 1:
arg_word = 'argument'
missing_keywords_str = "'%s'" % missing_keywords[0]
else:
arg_word = 'arguments'
and_join_str = ' and ' if count == 2 else ', and '
missing_keywords_str = ', '.join(
("'%s'" % mk) for mk in missing_keywords[:-1])
missing_keywords_str = and_join_str.join((
missing_keywords_str, ("'%s'" % missing_keywords[-1])))
msg = "%s() missing %d required keyword-only %s: %s"
raise TypeError(msg % (func_name, count, arg_word,
missing_keywords_str))
return func(*args, **kwargs)
require_wrapper.__wrapped__ = func
return require_wrapper
return require_kwargs_decorator
def exact_kwargs(*exact_keywords):
def exact_kwargs_decorator(func):
#restrict_kwargs(*exact_keywords)
#require_kwargs(*exact_keywords)
#functools.wraps(original_wrapped_function(func))
def exact_wrapper(*args, **kwargs):
return func(*args, **kwargs)
exact_wrapper.__wrapped__ = func
return exact_wrapper
return exact_kwargs_decorator
Some examples:
>>> #restrict_kwargs('five', 'six')
... def test_restrict_kwargs(arg1, arg2, *moreargs, **kwargs):
... return (arg1, arg2, moreargs, kwargs)
...
>>>
>>> #require_kwargs('five', 'six')
... def test_require_kwargs(arg1, arg2, *moreargs, **kwargs):
... return (arg1, arg2, moreargs, kwargs)
...
>>>
>>> #exact_kwargs('five', 'six')
... def test_exact_kwargs(arg1, arg2, *moreargs, **kwargs):
... return (arg1, arg2, moreargs, kwargs)
...
>>>
>>>
>>>
>>> test_restrict_kwargs(1, 2, 3, 4, five=5)
(1, 2, (3, 4), {'five': 5})
>>>
>>> test_restrict_kwargs(1, 2, 3, 4, five=5, six=6)
(1, 2, (3, 4), {'six': 6, 'five': 5})
>>>
>>> test_restrict_kwargs(1, 2, 3, 4, five=5, six=6, seven=7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "SO_31939890.py", line 19, in restrict_wrapper
raise TypeError(msg % (func.__name__, keyword))
TypeError: test_restrict_kwargs() got an unexpected keyword argument 'seven'
>>>
>>>
>>>
>>> test_require_kwargs(1, 2, 3, 4, five=5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "SO_31939890.py", line 49, in require_wrapper
missing_keywords_str))
TypeError: test_require_kwargs() missing 1 required keyword-only argument: 'six'
>>>
>>> test_require_kwargs(1, 2, 3, 4, five=5, six=6)
(1, 2, (3, 4), {'six': 6, 'five': 5})
>>>
>>> test_require_kwargs(1, 2, 3, 4, five=5, six=6, seven=7)
(1, 2, (3, 4), {'seven': 7, 'six': 6, 'five': 5})
>>>
>>>
>>>
>>> test_exact_kwargs(1, 2, 3, 4, five=5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "SO_31939890.py", line 20, in restrict_wrapper
return func(*args, **kwargs)
File "SO_31939890.py", line 49, in require_wrapper
missing_keywords_str))
TypeError: test_exact_kwargs() missing 1 required keyword-only argument: 'six'
>>>
>>> test_exact_kwargs(1, 2, 3, 4, five=5, six=6)
(1, 2, (3, 4), {'six': 6, 'five': 5})
>>>
>>> test_exact_kwargs(1, 2, 3, 4, five=5, six=6, seven=7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "SO_31939890.py", line 19, in restrict_wrapper
raise TypeError(msg % (func.__name__, keyword))
TypeError: test_exact_kwargs() got an unexpected keyword argument 'seven'
>>>
A star (*) is not a valid Python 2.7 identifier, it's an operator. I think you made a mistake while copying a code from the cookbook.
However, it's a valid code in Python 3, as Padraic Cunningham answered.
In python 2.*:
Parameters names derived as variables name laws in any programming languages. but in python 2.* STAR sign used before parameters names for determining special situation and single STAR sign as a parameter name raising error.
But in python 3.*:
A parameter that equal to STAR can't assign any value to this and next position parameters can't give value by position, and only can value by parameter name.
This is what I have so far
vdcm = (self.register(self.checkForInt), '%S')
roundsNumTB = Entry(self, validate = 'key', validatecommand = vdcm)
Then the checkForInt() function is defined as so
def checkForInt(self, S):
return (S.isDigit())
The entry box is meant to take an even number, and a number only; not characters. If a character is inputted, it is rejected. This will only work once though. If a character is inputted, the next keystroke which is an input is not rejected.
If someone could tell me how to make it permanently check to make sure the string is a digit, and an even one at that, it would be appreciated.
This is the error message I get if it's any help
Exception in Tkinter callback
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
return self.func(*args)
File "[py directory]", line 101, in checkForInt
return (S.isDigit())
AttributeError: 'str' object has no attribute 'isDigit'
I think the function call is isdigit() and not isDigit(), note the capitalization difference. If you want to test that the input is an integer and is even you would have to first convert the string using int() and test:
def checkForEvenInt(self, S):
if S.isdigit():
if int(S) % 2 is 0:
return True
return False
Keep in mind that Python is quite case-sensitive, including functions. For example, here's an iPython session:
In [1]: def my_func(): return True
In [2]: my_func()
Out[2]: True
In [3]: my_Func()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-25-ac6a0a3aba88> in <module>()
----> 1 my_Func()
NameError: name 'my_Func' is not defined
Working through "Learning Python" came across factory function. This textbook example works:
def maker(N):
def action(X):
return X ** N
return action
>>> maker(2)
<function action at 0x7f9087f008c0>
>>> o = maker(2)
>>> o(3)
8
>>> maker(2)
<function action at 0x7f9087f00230>
>>> maker(2)(3)
8
However when going deeper another level I have no idea how to call it:
>>> def superfunc(X):
... def func(Y):
... def subfunc(Z):
... return X + Y + Z
... return func
...
>>> superfunc()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: superfunc() takes exactly 1 argument (0 given)
>>> superfunc(1)
<function func at 0x7f9087f09500>
>>> superfunc(1)(2)
>>> superfunc(1)(2)(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>> superfunc(1)(2)
>>>
Why doesn't superfunc(1)(2)(3) work while maker(2)(3) does?
While this kind of nesting certainly doesn't look like a good, usable code to me, Python still accepts it as valid, so I'm curious as to how this can be called.
You get a TypeError because function func doesn't return anything (thus its return is NoneType). It should return subfunc:
>>> def superfunc(X):
... def func(Y):
... def subfunc(Z):
... return X + Y + Z
... return subfunc
... return func
...
A return is missing somewhere in your superfunc: you have a return for subfunc, but none for func.
superfunc corrected, with a calling example
def superfunc(X):
def func(Y):
def subfunc(Z):
return X + Y + Z
return subfunc
return func
print superfunc(1)(2)(3)
You forgot the return of the second function.
Here is the fixed function
def superfunct(x):
def func(y):
def subfunc(z):
return x + y + z
return subfunc
return func
print superfunct(1)(2)(3)