0

How do I make the following work,

for i in ['int', 'bool']:
  x = eval(f'match 1: \
               case {i}(): print(1)')

that is I want to run a match-case f-string inside an eval.

apostofes
  • 2,959
  • 5
  • 16
  • 31
  • Don't you need a parameter to the call to `int/bool`? – Nick Jun 14 '22 at 04:35
  • I am inspecting the match-case on the builtins. I was able to solve this problem, by using, `cc = compile(f'match 1:\n\tcase {i}(): print(1)','','single') y = eval(cc)` – apostofes Jun 14 '22 at 04:39
  • Parameter is optional – apostofes Jun 14 '22 at 06:11
  • But surely in that case they can't return `1`? `int()` will return `0` and `bool()` will return `False` – Nick Jun 14 '22 at 06:14
  • case is like a type check, it does not evaluate, so, `int()` would just check whether `1` is an integer (and print `1`), and `bool()` will just check whether `1` is a bool (and print nothing). it does not evaluate `int()` to `0` or `bool()` to `False` – apostofes Jun 14 '22 at 06:22
  • Ah yeah, I forgot about matching against classes... juggling too many languages in my head... – Nick Jun 14 '22 at 06:29

1 Answers1

1

eval only evaluates Python expressions. match is a statement. So you should use exec:

for i in ['int', 'bool']:
  exec(f'match 1:\n \
  case {i}(): print(1)')

(also beware of line breaks/indents inside f-strings)

Tranbi
  • 11,407
  • 6
  • 16
  • 33