python one line function definition

Question:

This must be simple, but as an only occasional python user, fighting some syntax.
This works:

def perms (xs):
    for x in itertools.permutations(xs): yield list(x) 

But this won’t parse:

def perms (xs): for x in itertools.permutations(xs): yield list(x) 

Is there some restriction on the one-line function syntax?
The body definition (for…) can be either two or one line by itself, and the def: can be one or two lines with a simple body, but combining the two fails.
Is there a syntax rule that excludes this?

Asked By: guthrie

||

Answers:

Yes, there are restrictions. No, you can’t do that. Simply put, you can skip one line feed but not two.

See here.

The reason for this is that it would allow you to do

if test1: if test2: print x
else:
    print y

Which is ambiguous.

Answered By: Lennart Regebro

If you must have one line just make it a lambda:

perms = lambda xs: (list(x) for x in itertools.permutations(xs))

Quite often, when you have a short for loop for generating data you can replace it with either list comprehension or a generator expression for approximately the same legibility in slightly less space.

Answered By: Sean Vieira

def perms (xs):

for x in itertools.permutations(xs): yield list(x)

You can use exec() to help this problem

exec('def perms (xs):n  for x in itertools.permutations(xs):n   yield list(x)n')

beware to insert indented spacing or chr(9) after n

Example for if Python in one line

for i in range(10):
 if (i==1):
  print(i)

exec('for i in range(10)n  if (i==1):n   print(i)n')

This is My project on GitHub to use exec to run Python program in interactive console mode

*note multiple line exec run only when end with ‘n’

In your case, I am not sure. But with some functions you can achive this by using semicolons.

>>> def hey(ho): print(ho); print(ho*2); return ho*3
...
>>> hey('you ')
you
you you
'you you you '
Answered By: jerik
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.