In Python, I wrote this:
bvar=mht.get_value()
temp=self.treemodel.insert(iter,0,(mht,False,*bvar))
I'm trying to expand bvar to the function call as arguments.
But then it returns:
File "./unobsoluttreemodel.py", line 65
temp=self.treemodel.insert(iter,0,(mht,False,*bvar))
^
SyntaxError: invalid syntax
What just happen? It should be correct right?
Update: this behavior was fixed in Python 3.5.0, see PEP-0448:
Unpacking is proposed to be allowed inside tuple, list, set, and dictionary displays:
*range(4), 4
# (0, 1, 2, 3, 4)
[*range(4), 4]
# [0, 1, 2, 3, 4]
{*range(4), 4}
# {0, 1, 2, 3, 4}
{'x': 1, **{'y': 2}}
# {'x': 1, 'y': 2}
If you want to pass the last argument as a tuple of (mnt, False, bvar[0], bvar[1], ...) you could use
temp = self.treemodel.insert(iter, 0, (mht,False)+tuple(bvar) )
The extended call syntax *b can only be used in calling functions, function arguments, and tuple unpacking on Python 3.x.
>>> def f(a, b, *c): print(a, b, c)
...
>>> x, *y = range(6)
>>> f(*y)
1 2 (3, 4, 5)
Tuple literal isn't in one of these cases, so it causes a syntax error.
>>> (1, *y)
File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target
Not it isn't right. Parameters expansion works only in function arguments, not inside tuples.
>>> def foo(a, b, c):
... print a, b, c
...
>>> data = (1, 2, 3)
>>> foo(*data)
1 2 3
>>> foo((*data,))
File "<stdin>", line 1
foo((*data,))
^
SyntaxError: invalid syntax
You appear to have an extra level of parentheses in there. Try:
temp=self.treemodel.insert(iter,0,mht,False,*bvar)
Your extra parentheses are trying to create a tuple using the * syntax, which is a syntax error.
Related
I tried to use * and ** to pass any number of arguments to a function. In "Learning Python" authored by Mark Lutz, it says to follow the order of positional (value) first, then a combination of keyword arguments (name=value) and *sequence, followed by **dict. However, I found that the positional arguments need to come first if present, but the rest of three, to certain extent, can be mixed in order.
Code keywords3.py:
def func(a, b=1, *pArgs, **kwArgs):
print("a = {0}, b = {1}".format(a,b))
print("Positional args = {}".format(pArgs))
print("Keyword args = {}".format(kwArgs))
By trial-and-error,
[1] Between keywords and **dict, they can be in any order...
>>> import keywords3 as j
>>> j.func(b = 3, **{'a':2,'c':4,'d':5})
a = 2, b = 3
Positional args = ()
Keyword args = {'d': 5, 'c': 4}
>>> j.func( **{'a':2}, b = 3, **{'c':4})
a = 2, b = 3
Positional args = ()
Keyword args = {'c': 4}
[2] Between positional args and *sequence, they can be in any order...
>>> j.func(*(2, 3), 4, *(5, 6))
a = 2, b = 3
Positional args = (4, 5, 6)
Keyword args = {}
>>> j.func(2, *(3, 4), 5, *(6,7), **{'c':8})
a = 2, b = 3
Positional args = (4, 5, 6, 7)
Keyword args = {'c': 8}
[3] In general, positional or *sequence arguments need to appear before keyword or **dict arguments.
>>> j.func(*(3, 4), 5, *(6,7), d=15, **{'c':8}, e=16)
a = 3, b = 4
Positional args = (5, 6, 7)
Keyword args = {'e': 16, 'd': 15, 'c': 8}
>>> j.func(d=15, 5, *(6,7), **{'c':8}, e=16)
File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument
>>> j.func(**{'a':2}, 5, *(6,7), **{'c':8}, e=16)
File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument unpacking
>>> j.func(**{'a':2}, *(6,7), **{'c':8}, e=16)
File "<stdin>", line 1
SyntaxError: iterable argument unpacking follows keyword argument unpacking
[4] One exception is that iterable argument unpacking *(6,7) following keyword argument is ok...
>>> j.func(f=5, *(6,7), **{'c':8}, e=16)
a = 6, b = 7
Positional args = ()
Keyword args = {'e': 16, 'f': 5, 'c': 8}
Are these observations correct? Please comment.
There is one single rule consistent with all your examples: positional arguments go before named arguments.
In all your examples, * and ** are unpacking operators. So, for example, when you write
f(1, *(2,3), 4)
the language gets
f(1,2,3,4)
They are all positional arguments, the language doesn't know the difference. Similarly for the ** operator.
However, when you violate that only rule, eg
j.func(**{'a':2}, 5, *(6,7), **{'c':8}, e=16)
you get an error, becuase, in this example, **{'a':2} is equivalent to a=2, which precedes the positional argument 5.
I am learning arbitrary value parameter and reading stackoverflow this and this answers and other tutorials I already understood what *args and **kwargs do in python but I am facing some errors. I have two doubts, first one is:
If I run this code print(w) then I am getting this output:
def hi(*w):
print(w)
kl = 1, 2, 3, 4
hi(kl)
output:
((1, 2, 3, 4),)
but if I run this code with print(*w) then I am getting this output:
code:
def hi(*w):
print(*w)
kl = 1, 2, 3, 4
hi(kl)
output:
(1, 2, 3, 4)
My second doubt is:
je = {"a": 2, "b": 4, "c": 6, 4: 5}
for j in je:
print(*je)
output
b a 4 c
b a 4 c
b a 4 c
b a 4 c
What exactly is *je doing there? How is it working in iteration?
When you use * in declaration of the arguments def hi(*w):, it means that all the arguments will be compressed to the tuple, e.g.:
hi(kl, kl) # ((1, 2, 3, 4), (1, 2, 3, 4))
After when you use print(*w) * run unpack of your tuple.
je={"a":2,"b":4,"c":6,4:5}
for j in je:
print(*je)
In every iteration you use unpack of your dict (you use je and get the keys of your dict like [j for j in je])
https://docs.python.org/2/tutorial/controlflow.html#tut-unpacking-arguments
Your first case, it's because you're passing kl into the function as a tuple, not as arbitrary values. Hence, *w will expand into a single element tuple with kl as the first value.
You're essentially calling:
hi((1, 2, 3, 4))
However, what I suspect you want is
hi(1, 2, 3, 4)
# or in your case
hi(*kl)
When printing in python 3, print is a function, so again. When w is a tuple and you call it like:
print(w)
# you'll get the tuple printed:
# (1, 2, 3, 4)
However, again, you can call it with arguments like:
print(1, 2, 3, 4)
# or in your case
print(*w)
# 1 2 3 4
For your second part, look at it converted to a list first:
list({"a":2,"b":4,"c":6,4:5})
# ["b", "a", 4, "c"]
# Note, dictionaries are unordered and so the list could be in any order.
If you were to then pass that to print using the * expansion:
print("b", "a", 4, c)
# or in your case
print(*["b", "a", 4, "c"])
Just note, that the * does the default iteration for you. If you wanted some other values, use je.values() or je.items()
I want to define a class Foo whose objects can be used like, foo[1, a=2].
I tried to achieve this by decorating the __getitem__ method of
Foo but with no success. Below is the example code.
def decorator(func):
def func_(*args, **kewargs):
if 'a' in kewargs:
args = list(args) + [kewargs['a']]
return func(*args)
else:
return func(*args)
return func_
class Foo(object):
#decorator
def __getitem__(self, *items):
return items
foo = Foo()
>>> foo.__getitem__(2, a=10)
(2, 10)
>>> foo[2, a=10]
SyntaxError: invalid syntax
So foo[...] is not equivalent to foo.__getitem__(...), something
behind the scene is done for the former. My question is what exactly and how
can I make foo[2, a=10] to work, if at all.
Python allows implicit tuple creation (without parentheses):
In [2]: tup = 1, 2, 3
In [3]: tup
Out[3]: (1, 2, 3)
And it works the same inside square brackets:
In [4]: d = {(1, 2, 3): 4}
In [5]: d[1, 2, 3]
Out[5]: 4
But (2, a=10) is not a valid tuple literal:
In [6]: (2, a=10)
File "<ipython-input-1-7dc03602f595>", line 1
(2, a=10)
^
SyntaxError: invalid syntax
Simply put, you can't make foo[2, a=10] to work, because it's a syntax error no matter how you tweak your __getitem__ implementation.
I'd probably define an ordinary method e.g. get and use it like Foo.get(2, a=10).
This is proposed for python 3.6
Using keyword arguments for indexing is currently a syntax error.
However, PEP472 (https://www.python.org/dev/peps/pep-0472/) proposes this addition to the python syntax.
Workarounds
The PEP also shows workarounds that are currently valid:
foo[2, "a":10] or foo[2, {"a":10}]
I wonder, is there a function in python -let's call it now apply- that does the following:
apply(f_1, 1) = f_1(1)
apply(f_2, (1, 2)) = f_1(1, 2)
...
apply(f_n, (1, 2,..., n)) = f_n(1, 2,..., n) # works with a tuple of proper length
Since it does exist in eg. A+ and Mathematica and it used to be really useful for me.
Cheers!
Python has language-level features for this, known as "argument unpacking", or just "splat".
# With positional arguments
args = (1, 2, 3)
f_1(*args)
# With keyword arguments
kwargs = {'first': 1, 'second': 2}
f_2(**kwargs)
You can use the * operator for the same effect:
f_1(*(1, 2)) = f_1(1, 2)
...
The expression following the * needn't be a tuple, it can be any expression that evaluates to a sequence.
Python also has a built-in apply function that does what you'd expect, but it's been obsolete in favor of the * operator since Python 2.3. If you need apply for some reason and want to avoid the taint of deprecation, it is trivial to implement one:
def my_apply(f, args):
return f(*args)
Yep, use the * operator on the list of arguments. For a practical example:
max(1, 2, 3, 4, 5) # normal invocation
=> 5
max(*[1, 2, 3, 4, 5]) # apply-like invocation
=> 5
Think of the second snippet as equivalent to apply(max, [1, 2, 3, 4, 5])
I am currently learning python coding and I come across this qns on a learning site:
Create a function that takes a sequence of inputs (may be a list, a tuple, or just a bunch of inputs). The function should return the minimum and the maximum of the list.
This are some of the test values that are using:
minmax(5,4)
4,5
minmax(5,4,8,3,5,7,4)
3,8
minmax([5,4,6])
4,6
minmax(5.1,4.2,68.34,129.1,-90.3)
-90.3,129.1
And I had tried doing it this way but when the parameter is a list, I can't seems to convert it into a tuple and find the max and min.
Here is what I had tried:
def minmax(*a):
b = tuple(a)
minNum = min(b)
maxNum = max(b)
c = (minNum, maxNum)
return c
When a list is taken in, the return result is ([5, 4, 6], [5, 4, 6])
def minmax(*a):
if len(a) == 1: # Single (list, tuple, or scalar) argument
try:
return minmax(*a[0]) # Expansion of sequence elements, if possible
except TypeError: # Case of minmax(42)
pass # The general code below handles this directly
return (min(a), max(a))
>>> minmax(3, 5, 1, 10)
(1, 10)
>>> minmax([3, 5, 1, 10])
(1, 10)
>>> minmax((42, 123, -12))
(-12, 123)
>>> minmax(42)
42
This works in more cases than the built-in min() and max(), which do not work on a single scalar argument (min(42)).
>>> min(42)
TypeError: 'int' object is not iterable
It is however possible to write a simpler version that behaves like the built-in min() and max() (see my other answer, for instance).
This works by forcing min() to be given strictly more than 1 element, except in the special case of minmax(42), which calls min((42,)).
To be able to handle different ways of passing in arguments, you need to have some conditions to handle each case.
>>> def minmax(*a):
... if len(a) == 1 and hasattr(a[0], '__getitem__'):
... # handle a single sequence passed in
... return min(a[0]), max(a[0])
... # handle values passed in
... return min(a), max(a)
...
>>> minmax(5, 4)
(4, 5)
>>> minmax(5, 4, 8, 3, 5, 7, 4)
(3, 8)
>>> minmax([5, 4, 6])
(4, 6)
>>> minmax(5.1, 4.2, 68.34, 129.1, -90.3)
(-90.3, 129.1)
A simpler but slightly less powerful solution that mirrors my other solution is:
def minmax(*a):
if len(a) == 1: # Single (list or tuple) argument
return (min(a[0]), max(a[0]))
return minmax(a) # Single tuple argument given to minmax()
This version forces min() to be given a single (list or tuple) argument.
It behaves like the built-in min() and max(): min(42) and minmax(42) both raise an exception:
>>> minmax(3, 5, 1, 10)
(1, 10)
>>> minmax([3, 5, 1, 10])
(1, 10)
>>> minmax((42, 123, -12))
(-12, 123)
>>> minmax(42)
TypeError: 'int' object is not iterable
>>> min(42)
TypeError: 'int' object is not iterable