X, = ... - Is This Trailing Comma the Comma Operator

x, = ... - is this trailing comma the comma operator?

ax.plot() returns a tuple with one element. By adding the comma to the assignment target list, you ask Python to unpack the return value and assign it to each variable named to the left in turn.

Most often, you see this being applied for functions with more than one return value:

base, ext = os.path.splitext(filename)

The left-hand side can, however, contain any number of elements, and provided it is a tuple or list of variables the unpacking will take place.

In Python, it's the comma that makes something a tuple:

>>> 1
1
>>> 1,
(1,)

The parenthesis are optional in most locations. You could rewrite the original code with parenthesis without changing the meaning:

(line,) = ax.plot(x, np.sin(x))

Or you could use list syntax too:

[line] = ax.plot(x, np.sin(x))

Or, you could recast it to lines that do not use tuple unpacking:

line = ax.plot(x, np.sin(x))[0]

or

lines = ax.plot(x, np.sin(x))

def animate(i):
lines[0].set_ydata(np.sin(x+i/10.0)) # update the data
return lines

#Init only required for blitting to give a clean slate.
def init():
lines[0].set_ydata(np.ma.array(x, mask=True))
return lines

For full details on how assignments work with respect to unpacking, see the Assignment Statements documentation.

What does the comma , after a variable mean in Python?

You can find it on 5. Data Structures - Python 3.6.3 documentation

A tuple consists of a number of values separated by commas
[...]
Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing

What is the comma doing in this assignment?

Python allows you to assign more than one variable at once, like this:

a, b = 1, 2

The way this works is by treating the left hand side of the assignment a, b as a tuple, and assigning each element in the tuple 1, 2 on the right hand side to it.

Since tuples can have just one element, the following also works:

a, = 1,

The right hand side of a multiple assignment doesn't have to be a tuple. Any iterable will do, as long as the number of elements on each side is the same:

a, b, c = "three little pigs".split()

If the number of elements doesn't match:

a, b, c = "oh", "no"

... you get a ValueError:

ValueError: not enough values to unpack (expected 3, got 2)

Putting all of the above together, then, your function:

def find_project(project_name):    
projects = get_projects()
try:
match, = (proj for proj in projects if proj["name"].strip() == project_name)
return match
except ValueError:
return None

... iterates over the generator expression

(proj for proj in projects if proj["name"].strip() == project_name)

... and if the result has one element, assigns that element to match. If not, ValueError is raised (and caught by the except clause), no assignment happens, and None is returned .

Two things to note:

  1. The comma , is easy to miss when reading code. An alternative would be to use list syntax on the left hand side:

    [match] = (proj for proj in projects if proj["name"].strip() == project_name)

    ... which has the same effect.

  2. When the right hand side is a generator expression (or some other kind of iterator), you can use next() with a default value instead:

    def find_project(project_name):    
    projects = get_projects()
    it = (proj for proj in projects if proj["name"].strip() == project_name)
    return next(it, None)

    ... which is shorter and more readable.

In Python, what is the purpose of a trailing comma in a return statement?

Basically putting a comma after the return statement casts the parameter that you are returning to a tuple containing the parameter. It won't affect the value of the parameter at all, but rather how it is packaged. Using your example functions

def no_trailing_comma(x):
return x + [10]

def trailing_comma(x):
return x + [10],

data = [1, 2, 3]

no_comma_value = no_trailing_comma(data)
comma_value = trailing_comma(data)

print("The return type is", type(no_comma_value))
print("The return type is", type(comma_value))

This code would yield:

The return type is <class 'list'>

The return type is <class 'tuple'>

You should have seen a difference in the print outputs (i.e. one being in a tuple) but this could be a 3.6 thing that I don't know about yet.

Mystical comma in a Python expression

It's just unpacking a 1-tuple. eg:

line, = ('foo',)   # same as line = 'foo' in this example

compare with

line1, line2 = ('foo', 'bar') # unpack a 2-tuple

etc.

int a[] = {1,2,}; Why is a trailing comma in an initializer-list allowed?

It makes it easier to generate source code, and also to write code which can be easily extended at a later date. Consider what's required to add an extra entry to:

int a[] = {
1,
2,
3
};

... you have to add the comma to the existing line and add a new line. Compare that with the case where the three already has a comma after it, where you just have to add a line. Likewise if you want to remove a line you can do so without worrying about whether it's the last line or not, and you can reorder lines without fiddling about with commas. Basically it means there's a uniformity in how you treat the lines.

Now think about generating code. Something like (pseudo-code):

output("int a[] = {");
for (int i = 0; i < items.length; i++) {
output("%s, ", items[i]);
}
output("};");

No need to worry about whether the current item you're writing out is the first or the last. Much simpler.

x, = ... - is this trailing comma the comma operator?

ax.plot() returns a tuple with one element. By adding the comma to the assignment target list, you ask Python to unpack the return value and assign it to each variable named to the left in turn.

Most often, you see this being applied for functions with more than one return value:

base, ext = os.path.splitext(filename)

The left-hand side can, however, contain any number of elements, and provided it is a tuple or list of variables the unpacking will take place.

In Python, it's the comma that makes something a tuple:

>>> 1
1
>>> 1,
(1,)

The parenthesis are optional in most locations. You could rewrite the original code with parenthesis without changing the meaning:

(line,) = ax.plot(x, np.sin(x))

Or you could use list syntax too:

[line] = ax.plot(x, np.sin(x))

Or, you could recast it to lines that do not use tuple unpacking:

line = ax.plot(x, np.sin(x))[0]

or

lines = ax.plot(x, np.sin(x))

def animate(i):
lines[0].set_ydata(np.sin(x+i/10.0)) # update the data
return lines

#Init only required for blitting to give a clean slate.
def init():
lines[0].set_ydata(np.ma.array(x, mask=True))
return lines

For full details on how assignments work with respect to unpacking, see the Assignment Statements documentation.

trailing comma in assigning argument parameter in 'sched.scheduler.enter'

Tuples only need , commas, they don't need () parenthesis, except when they do! So for example in:

x = 1, 2, 3
y = (1, 2, 3)

And:

x = 1,
y = (1,)

In both cases x and y are identical. But in your case:

s.enter(5, 1, do_something, argument=(sc,))
s.enter(5, 1, do_something, argument=sc,)

Are, as you found out, not the same. Why?

Well in the second case argument=sc, the , is interpreted to be part of the ,'s of the parameter list, so it is not considered as indicating a tuple(). And in this case, you need the (sc,) to build a tuple()



Related Topics



Leave a reply



Submit