Wildcards in Python?

Over the years, I have noticed the variable "wildcard" in different bits and pieces of Python that I came across. I assumed that it works like Haskell: allows you to put a variable where formal parameters are required, but not to bind it.

I used this, for example, on the left side of the destination for unpacking, if I do not need one of the variables.

For instance:

_, extension = os.path.splitext(filename)

So, when I wrote something similar to this today:

(lambda (x,_,_): x)((1,2,3))

those. I tried to associate the underscore twice, I received a syntax error. I was surprised to see that _ is indeed a real variable:

(lambda (x,_,z): _)((1,2,3))
> 2

It looks like _it's just a variable name, like any other.

bona fide, , (, ), ?

+5
5

Python .

_ . , _ , _ , . - "", _ , .

, , . , _ _ gettext.

lambda, lambda x, *args: ..., , . , , , dummy. range() s for i in range(n) i.

. ( ), , lambda x, *args: ... . Python 3.x, . mipadi answer.

+4

, Python Haskell _. Python _ "throwaway", , , , (, ).

:

lambda tup: tup[0]

lambda tup: tup[1]

, .

+3

. Python Haskell. , , - , itertools .

, :

def f(x, *args, **kwargs):
    return x

*args ( args). kwargs.

, , . . , / , ( ):

def make_func(s):
    def f(*trash, **more_trash):
        print s
    return f

f1 = make_func('hello')
f2 = make_func('world')
f1(1,2,'ham','spam')
f2(1,2,a=1,b=2)

:

>>> hello
>>> world

@rplnt, :

funcs = []
for s in ('hello','world'):
    def f():
        print s
    funcs.append(f)

for f in funcs:
    f()

:

>>> world
>>> world

.

+3

, :

class _: 
    def __eq__(x,y): return true
_=_() #always create a new _ instance if used, the class name itself is not needed anymore

[(a,b) for (a,_,_,b) in [(1,2,3,4),(5,6,7,8)]]

[(1, 4), (5, 8)] 

, , Haskells Python.

+2

- . .

(lambda (x, _1, _2): x)((1,2,3))
+1

All Articles