omry / omegaconf

Flexible Python configuration system. The last one you will ever need.
BSD 3-Clause "New" or "Revised" License
1.94k stars 105 forks source link

Allow for custom resolvers with no arguments #1060

Closed markcoletti closed 10 months ago

markcoletti commented 1 year ago

Allow for creating resolvers that take no arguments. E.g., OmegaConf.register_new_resolver("cpus", lambda : os.cpu_count)

Currently attempts at this throws an exception.

24hours commented 1 year ago

Passing fake value should work ?

${cpus:temp}

OmegaConf.register_new_resolver("cpus", lambda x : os.cpu_count)

markcoletti commented 1 year ago

That's a kludge that works but is a bit ugly. It'd be cleaner and more intuitive if the package supports my original intent.

Galileo-Galilei commented 10 months ago

I'd love to have this feature too. If you are open to PR's and can give me a rough sketch of what will be impacted in the code, I can give it a try.

odelalleau commented 10 months ago

I just tried it and this is working => closing the issue (please re-open with a specific example if the issue still persists on your side)

goldegard commented 4 months ago

Hi, I'm trying to use custom resolvers with no params and I'm hitting the same issue reported here. Minimal reproducible example:

import random

from omegaconf import OmegaConf

OmegaConf.register_new_resolver("plus_10", lambda x: x + 10)
OmegaConf.register_new_resolver("random_number", lambda: random.randint(0, 1000))

c = OmegaConf.create(
    {
        "key": "${plus_10:990}",
        "key2": "${random_number}",
    }
)

print(c.key, c.key2)

Output:

...
omegaconf.errors.InterpolationKeyError: Interpolation key 'random_number' not found
    full_key: key2
    object_type=dict

Interestingly, adding : with or without any dummy parameter seems to work, but it's not very idiomatic:

import random

from omegaconf import OmegaConf

OmegaConf.register_new_resolver("plus_10", lambda x: x + 10)
OmegaConf.register_new_resolver("random_number", lambda: random.randint(0, 1000))

c = OmegaConf.create(
    {
        "key": "${plus_10:990}",
        "key2": "${random_number:}",
    }
)

print(c.key, c.key2)

Any thoughts?

Additional context