sergiocorreia / panflute

An Pythonic alternative to John MacFarlane's pandocfilters, with extra helper functions
http://scorreia.com/software/panflute/
BSD 3-Clause "New" or "Revised" License
500 stars 59 forks source link

Can panflute support match-case? #238

Closed Zhaopudark closed 3 months ago

Zhaopudark commented 9 months ago

Thanks for this great project! 😄 I'm working on a Python module, pandoc-filter that based on this project. And I find it will be convenient if panflute can support the match-case mechanism better.

The basic match-case mechanism is as:

content = ['1','2','3']
match content:
    case [str('1'),*_]:
        print("match ok")
    case _:
        print("match failed")

class MyStr:
    def __init__(self, text):
        self.text = text
content = [MyStr('1'),MyStr('2'),MyStr('3')]

match content:
    case [MyStr,*_]:
        print("match ok")
    case _:
        print("match failed")

And, I want it to work on panflute classes. The expected syntax is as:

import panflute as pf  
content = [pf.Str('1'),pf.Str('2'),pf.Str('3')]

match content:
    case [pf.Str,*_]:
        print("match ok")
    case _:
        print("match failed")
# Expect match ok

The above codes do not work in the current panflute version 2.3.0.

Maybe I do not understand match-case mechanism well and do not know panflute fully. My current alternative is

import panflute as pf  
content = [pf.Str('1'),pf.Space(),pf.Para(pf.Str('2'))]

match content:
    case [pf_str,*_] if isinstance(pf_str,pf.Str):
        print("match ok")
    case _:
        print("match failed")

So, I think it will be convenient if panflute can support the match-case mechanism better. Thanks in advance. 🌞

NMarkgraf commented 3 months ago

I'm sure, you are right! You do not understand the match-case mechanism. ;-)

pf.Str is some kind of type not a variable, so your work around seems to me the only working way. Sorry. :-(

Zhaopudark commented 3 months ago

@NMarkgraf Thanks. I will consider the problem and paradigms more prudently later.