Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lambda functions can be defined in config #374

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions skypy/pipeline/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,14 @@ def construct_function(self, name, node):

return (function, args, kwargs)

def construct_lambda(self, node):

lambda_val = node.value

assign_lambda_to_temp = 'temp = lambda {}'.format(lambda_val)
exec(assign_lambda_to_temp, globals())
return temp
JonathanDHarris marked this conversation as resolved.
Show resolved Hide resolved

def construct_quantity(self, node):
value = self.construct_scalar(node)
return Quantity(value)
Expand All @@ -89,6 +97,9 @@ def construct_quantity(self, node):
# constructor for generic functions
SkyPyLoader.add_multi_constructor('!', SkyPyLoader.construct_function)

# constructor for lambda functions
SkyPyLoader.add_constructor('!lambda', SkyPyLoader.construct_lambda)

# constructor for quantities
SkyPyLoader.add_constructor('!quantity', SkyPyLoader.construct_quantity)
# Implicitly resolve quantities using the regex from astropy
Expand Down
3 changes: 3 additions & 0 deletions skypy/pipeline/tests/data/lambda_function.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
a: 0.5
tau: !lambda 'a : 1. / a'
twice: !lambda 'a : a * 2'
8 changes: 8 additions & 0 deletions skypy/pipeline/tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,11 @@ def test_kwarg_must_be_strings():
with pytest.raises(ValueError) as e:
load_skypy_yaml(filename)
assert("Invalid key found in config" in e.value.args[0])


def test_lambda_functions():
filename = get_pkg_data_filename('data/lambda_function.yml')
config = load_skypy_yaml(filename)
a = config['a']
assert config['tau'](a) == 1. / a
assert config['twice'](a) == 1.0