简体   繁体   中英

Simple way to make python 3.10 code compatible for python 3.9 and below to use match

I am looking for a simple way to make my code compatible for both python 3.10 and below.

Toy-Example:

class MatchSomething

   # for 3.10
   def match_matcher(self, input=23)
      match input:
         case 23:
            print("TWENTYTHREE")

   # For below 3.10
   def if_matcher(self, input=23)
      if input == 23:
         print("TWENTYTHREE")


When I import this class under a python 3.9 environment, I obviously get "SyntaxError: invalid syntax" since it does not now the match pattern.

Is there a very simple way to solve this problem like a decorator or so? I was thinking about putting both functions in a separate file and only import the respectively compatible function depending on the python version (see answer from @ErnestBidouille). However this would also not be a very nice solution since it will reduce the readability of the code (the function will have a very crucial role)

Edit: The reason why I would like to use match over if-conditions is to increase performance.

A bit strange question, but I would do this if it is an absolute necessity.

One file `match_something.py for 3.9 and below:

class MatchSomething:

    # For below 3.10
    def if_matcher(self, input=23):
        if input == 23:
            print("TWENTYTHREE")

One file `match_something_10.py for >= 3.10:

class MatchSomething:

   # for 3.10
   def match_matcher(self, input=23):
      match input:
         case 23:
            print("TWENTYTHREE")

and one main file which import correct class version:

import sys

if sys.version_info >= (3, 10):
    from match_something_10 import MatchSomething
elif sys.version_info.major >= 3:
    from match_something import MatchSomething
else:
    raise NotImplementedError('Not working with Python 2')

print(MatchSomething)

You just can't override a syntax error, since the word match doesn't exist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM