If you're really interested, you can get an idea of how fast a function will run using dis; more lines is probably worse:
return at end:
4 0 LOAD_FAST 0 (a)
3 LOAD_CONST 1 (0)
6 COMPARE_OP 4 (>)
9 POP_JUMP_IF_FALSE 21
5 12 LOAD_CONST 2 (1)
15 STORE_FAST 1 (num)
18 JUMP_FORWARD 6 (to 27)
7 >> 21 LOAD_CONST 3 (-1)
24 STORE_FAST 1 (num)
8 >> 27 LOAD_FAST 1 (num)
30 RETURN_VALUE
11 lines, pretty fast.
return in if:
13 0 LOAD_FAST 0 (a)
3 LOAD_CONST 1 (0)
6 COMPARE_OP 4 (>)
9 POP_JUMP_IF_FALSE 16
14 12 LOAD_CONST 2 (1)
15 RETURN_VALUE
16 >> 16 LOAD_CONST 3 (-1)
19 RETURN_VALUE
20 LOAD_CONST 0 (None)
23 RETURN_VALUE
10 lines, probably slightly faster.
And thefourtheye's suggestion:
def func(a):
return 1 if a > 0 else -1
Gives:
21 0 LOAD_FAST 0 (a)
3 LOAD_CONST 1 (0)
6 COMPARE_OP 4 (>)
9 POP_JUMP_IF_FALSE 16
22 12 LOAD_CONST 2 (1)
15 RETURN_VALUE
23 >> 16 LOAD_CONST 3 (-1)
19 RETURN_VALUE
8 lines, winner (by two lines that will never run)!
But this is definitely the premature optimisation your mother warned you about!
return 1 if a > 0 else -1