[Python] glob.translate incorrectly matches path separator when using ranges

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    I am playing around with new Python 3.13 function glob.translate. Docs say that:


    By default wildcards do no match path separators, and * pattern segments match precisely one path segment.
    ​

    This can be seen in:

    import glob
    import re

    r = re.compile(glob.translate('a?c', seps=['/'])))
    print(r) # (?s:a[^/]c)\Z
    print(r.match('abc')) # true
    print(r.match('a/c')) # false


    I would therefore expect that any range which includes path separator would automatically exclude it, but it is not the case:

    import glob
    import re

    r = re.compile(glob.translate('a[%-0]c', seps=['/'])))
    print(r) # (?s:a[%-0]c)\Z
    print(r.match('a0c')) # true
    print(r.match('a/c')) # true


    Are my expectations correct? The glob module is documented to behave as Unix, but the same glob does not match the path separator in my bash shell:

    $ mkdir a
    $ touch a/c
    $ ls -1 a/c
    a/c
    $ ls -1 [a-c]/[a-c] # check glob support
    a/c
    $ ls -1 a[%-0]c
    ls: cannot access 'a[%-0]c': No such file or directory
    $ shopt -s failglob
    $ ls -1 a[%-0]c
    -bash: no match: a[%-0]b


    So it looks to me like a bug in Python, which should instead translate the range [%-0] to [%-.0] or use negative lookahead (?!\/)[%-0].

    Continue reading...

Compartilhe esta Página