r1chardj0n3s / parse

Parse strings using a specification based on the Python format() syntax.
http://pypi.python.org/pypi/parse
MIT License
1.72k stars 101 forks source link

Use patterns inductively doesn't seem to work #160

Closed mcoulont closed 1 year ago

mcoulont commented 1 year ago

Hello

I define a type and then try to use it to define another type:

from parse import parse, with_pattern

@with_pattern("[A-Z]+")
def parse_identifiant(text):
    return text

@with_pattern("v{:Identifiant}")
def parse_videntifiant(text):
    return text

types = dict(Identifiant=parse_identifiant, Videntifiant=parse_videntifiant)

if None == parse("av{:Identifiant}", "avSTUFF", types):
    print("The first messes up")
else:
    print("The first works")

if None == parse("a{:Videntifiant}", "avSTUFF", types):
    print("The second messes up")
else:
    print("The second works")

I don't understand why this program outputs

The first works
The second messes up

although the description of the type Videntifiant is v{:Identifiant}.

Thanks for your package by the way

mcoulont commented 1 year ago

I think I can answer my own question. Someone will reopen the issue if needs be.

As patterns are stored in Python dictionaries and as keys/values of dictionaries are not supposed to depend one another, it is normal that it doesn't work.

A workaround to avoid code duplication is:

regexIdentifiant = [A-Z]+
@with_pattern(regexIdentifiant)
def parse_identifiant(text):
    return text

regexVidentifiant = "v" + regexIdentifiant
@with_pattern(regexVidentifiant)
def parse_videntifiant(text):
    return text