zeroSteiner / rule-engine

A lightweight, optionally typed expression language with a custom grammar for matching arbitrary Python objects.
https://zerosteiner.github.io/rule-engine/
BSD 3-Clause "New" or "Revised" License
445 stars 54 forks source link

Support for List index #5

Closed farzad-xgen closed 4 years ago

farzad-xgen commented 4 years ago

Hi, is it possible to support lists with indexes? Like a[1] == 1?

zeroSteiner commented 4 years ago

As of now this is not possible. It is however the number 1 item on my to do list, I just haven't gotten around to it yet.

farzad-xgen commented 4 years ago

Thanks for the reply. I came up with a solution (not a perfect one) with a custom resolver and it actually works:

def adv_resolve_item(thing, name):
    if name[0] == '_' and str(name[1:]).isnumeric():
        if not isinstance(thing, list):
            raise rule_engine.SymbolResolutionError(name, thing=thing)
        # List index
        ind = int(str(name[1:]))
        try:
            return thing[ind]
        except:
            return None
    if not isinstance(thing, collections.abc.Iterable):
        raise rule_engine.SymbolResolutionError(name, thing=thing)
    if name not in thing:
        raise rule_engine.SymbolResolutionError(name, thing=thing)
    return thing[name]

This way, you can use name._ind (ind is integer) which is name[ind].

zeroSteiner commented 4 years ago

That's awesome.

zeroSteiner commented 4 years ago

I just merged this into master. The functionality will be included in the 2.1 release. It's strictly get item support like thing[0] in Python, there's no slice support yet like thing[0:2]. I'll probably look to do a 2.1 release in 3-10 days once I've had a bit more time to review and test this.

zeroSteiner commented 4 years ago

Completed this in the v2.1.0 release which is now on PyPi https://pypi.org/project/rule-engine/2.1.0/.