7

Scala has the apply() function.

I am new to Python and I am wondering how should I write the following one-liner:

(part_a, part_b) = (lambda x: re.search(r"(\w+)_(\d+)", x).groups())(input_string) 

I would feel better with something like:

(part_a, part_b) = input_string.apply(lambda x: re.search(r"(\w+)_(\d+)", x).groups()) 

Am I wrong from a FF viewpoint? Is there such construction in Python?

Edit: I know about the poorly picked snippet.

8
  • No, there isn't, but it would be easy enough to write your own such that part_a, part_b = apply(lambda ...: ..., input_string) worked. Commented Aug 27, 2015 at 12:22
  • 1
    That would require all objects to have an apply method, which they don't. So I'm afraid that you have to live with that. Note that what you would feel better with is a longer way to write the same thing. Commented Aug 27, 2015 at 12:23
  • 3
    Python has had an apply function since the beginning too, but since apply(fn, args, kwargs) == fn(*args, **kwargs) there is little use for it anymore.. Commented Aug 27, 2015 at 12:23
  • 1
    Maybe functools.partial()? Commented Aug 27, 2015 at 12:24
  • 1
    why are you doing a lambda function if you are going to use it just once? whats wrong with re.search(r"(\w+)_(\d+)", input_string).groups()? Commented Aug 27, 2015 at 12:25

5 Answers 5

12

When writing Haskell write Haskell. When writing Python just write Python:

part_a, part_b = re.search(r"(\w+)_(\d+)", input_string).groups() 
Sign up to request clarification or add additional context in comments.

Comments

3

If you're using a Python without apply, you could always write it yourself...

def apply(fn, args=(), kwargs=None): if kwargs is None: kwargs = {} return fn(*args, **kwargs) 

just because you could, doesn't mean you should..

Comments

1

Python does not have such a construct; what would be the point? lambda x: ... is a function, and therefore it should be used like a normal function, i.e., as (lambda x: ...)(input_string) as in your first snippet.

However, in your case, I see no reason why you should even bother with a lambda; just do:

(part_a, part_b) = re.search(r"(\w+)_(\d+)", input_string).groups() 

Comments

1

If you're concerned about re-use, you could compile the regex:

rx = re.compile(r"(\w+)_(\d+)") a, b = rx.search(input_string).groups() 

1 Comment

I tend to do it for documentation more than performance (assuming I can give rx an informative name).
1

Python used to have a apply function (docs), but it has been removed in python 3, since it was unnecessary and against python's principle that there should be only one way to do a particular thing.

Say, we have a function called "func", we can easily call func(*args) instead of apply(func, args).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.