How to use from_config method in avocado

Best Python code snippet using avocado_python

config.py

Source:config.py Github

copy

Full Screen

...97 @configurable98 def __init__(self, a, b=2, c=3):99 pass100 @classmethod101 def from_config(cls, cfg): # 'cfg' must be the first argument102 # Returns kwargs to be passed to __init__103 return {"a": cfg.A, "b": cfg.B}104 a1 = A(a=1, b=2) # regular construction105 a2 = A(cfg) # construct with a cfg106 a3 = A(cfg, b=3, c=4) # construct with extra overwrite107 # Usage 2: Decorator on any function. Needs an extra from_config argument:108 @configurable(from_config=lambda cfg: {"a: cfg.A, "b": cfg.B})109 def a_func(a, b=2, c=3):110 pass111 a1 = a_func(a=1, b=2) # regular call112 a2 = a_func(cfg) # call with a cfg113 a3 = a_func(cfg, b=3, c=4) # call with extra overwrite114 Args:115 init_func (callable): a class's ``__init__`` method in usage 1. The116 class must have a ``from_config`` classmethod which takes `cfg` as117 the first argument.118 from_config (callable): the from_config function in usage 2. It must take `cfg`119 as its first argument.120 """121 if init_func is not None:122 assert (123 inspect.isfunction(init_func)124 and from_config is None125 and init_func.__name__ == "__init__"126 ), "Incorrect use of @configurable. Check API documentation for examples."127 @functools.wraps(init_func)128 def wrapped(self, *args, **kwargs):129 try:130 from_config_func = type(self).from_config131 except AttributeError as e:132 raise AttributeError(133 "Class with @configurable must have a 'from_config' classmethod."134 ) from e135 if not inspect.ismethod(from_config_func):136 raise TypeError("Class with @configurable must have a 'from_config' classmethod.")137 if _called_with_cfg(*args, **kwargs):138 explicit_args = _get_args_from_config(from_config_func, *args, **kwargs)139 init_func(self, **explicit_args)140 else:141 init_func(self, *args, **kwargs)142 return wrapped143 else:144 if from_config is None:145 return configurable # @configurable() is made equivalent to @configurable146 assert inspect.isfunction(147 from_config148 ), "from_config argument of configurable must be a function!"149 def wrapper(orig_func):150 @functools.wraps(orig_func)151 def wrapped(*args, **kwargs):152 if _called_with_cfg(*args, **kwargs):153 explicit_args = _get_args_from_config(from_config, *args, **kwargs)154 return orig_func(**explicit_args)155 else:156 return orig_func(*args, **kwargs)157 return wrapped158 return wrapper159def _get_args_from_config(from_config_func, *args, **kwargs):160 """161 Use `from_config` to obtain explicit arguments.162 Returns:163 dict: arguments to be used for cls.__init__164 """165 signature = inspect.signature(from_config_func)166 if list(signature.parameters.keys())[0] != "cfg":167 if inspect.isfunction(from_config_func):168 name = from_config_func.__name__169 else:170 name = f"{from_config_func.__self__}.from_config"171 raise TypeError(f"{name} must take 'cfg' as the first argument!")172 support_var_arg = any(173 param.kind in [param.VAR_POSITIONAL, param.VAR_KEYWORD]...

Full Screen

Full Screen

test_framework_agnostic_components.py

Source:test_framework_agnostic_components.py Github

copy

Full Screen

...34 return tf.add(self.prop_b, value)35class NonAbstractChildOfDummyComponent(DummyComponent):36 pass37class AbstractDummyComponent(DummyComponent, metaclass=ABCMeta):38 """Used for testing `from_config()`.39 """40 @abstractmethod41 def some_abstract_method(self):42 raise NotImplementedError43class TestFrameWorkAgnosticComponents(unittest.TestCase):44 """45 Tests the Component base class to implement framework-agnostic functional46 units.47 """48 def test_dummy_components(self):49 # Bazel makes it hard to find files specified in `args`50 # (and `data`).51 # Use the true absolute path.52 script_dir = Path(__file__).parent53 abs_path = script_dir.absolute()54 for fw, sess in framework_iterator(session=True):55 fw_ = fw if fw != "tfe" else "tf"56 # Try to create from an abstract class w/o default constructor.57 # Expect None.58 test = from_config({59 "type": AbstractDummyComponent,60 "framework": fw_61 })62 check(test, None)63 # Create a Component via python API (config dict).64 component = from_config(65 dict(66 type=DummyComponent,67 prop_a=1.0,68 prop_d="non_default",69 framework=fw_))70 check(component.prop_d, "non_default")71 # Create a tf Component from json file.72 config_file = str(abs_path.joinpath("dummy_config.json"))73 component = from_config(config_file, framework=fw_)74 check(component.prop_c, "default")75 check(component.prop_d, 4) # default76 value = component.add(3.3)77 if sess:78 value = sess.run(value)79 check(value, 5.3) # prop_b == 2.080 # Create a torch Component from yaml file.81 config_file = str(abs_path.joinpath("dummy_config.yml"))82 component = from_config(config_file, framework=fw_)83 check(component.prop_a, "something else")84 check(component.prop_d, 3)85 value = component.add(1.2)86 if sess:87 value = sess.run(value)88 check(value, np.array([2.2])) # prop_b == 1.089 # Create tf Component from json-string (e.g. on command line).90 component = from_config(91 '{"type": "ray.rllib.utils.tests.'92 'test_framework_agnostic_components.DummyComponent", '93 '"prop_a": "A", "prop_b": -1.0, "prop_c": "non-default", '94 '"framework": "' + fw_ + '"}')95 check(component.prop_a, "A")96 check(component.prop_d, 4) # default97 value = component.add(-1.1)98 if sess:99 value = sess.run(value)100 check(value, -2.1) # prop_b == -1.0101 # Test recognizing default module path.102 component = from_config(103 DummyComponent, '{"type": "NonAbstractChildOfDummyComponent", '104 '"prop_a": "A", "prop_b": -1.0, "prop_c": "non-default",'105 '"framework": "' + fw_ + '"}')106 check(component.prop_a, "A")107 check(component.prop_d, 4) # default108 value = component.add(-1.1)109 if sess:110 value = sess.run(value)111 check(value, -2.1) # prop_b == -1.0112 # Test recognizing default package path.113 scope = None114 if sess:115 scope = tf1.variable_scope("exploration_object")116 scope.__enter__()117 component = from_config(118 Exploration, {119 "type": "EpsilonGreedy",120 "action_space": Discrete(2),121 "framework": fw_,122 "num_workers": 0,123 "worker_index": 0,124 "policy_config": {},125 "model": None126 })127 if scope:128 scope.__exit__(None, None, None)129 check(component.epsilon_schedule.outside_value, 0.05) # default130 # Create torch Component from yaml-string.131 component = from_config(132 "type: ray.rllib.utils.tests."133 "test_framework_agnostic_components.DummyComponent\n"134 "prop_a: B\nprop_b: -1.5\nprop_c: non-default\nframework: "135 "{}".format(fw_))136 check(component.prop_a, "B")137 check(component.prop_d, 4) # default138 value = component.add(-5.1)139 if sess:140 value = sess.run(value)141 check(value, np.array([-6.6])) # prop_b == -1.5142 def test_unregistered_envs(self):143 """Tests, whether an Env can be specified simply by its absolute class.144 """145 env_cls = "ray.rllib.examples.env.stateless_cartpole.StatelessCartPole"146 env = from_config(env_cls, {"config": 42.0})147 state = env.reset()148 self.assertTrue(state.shape == (2, ))149if __name__ == "__main__":150 import pytest151 import sys...

Full Screen

Full Screen

utils.py

Source:utils.py Github

copy

Full Screen

1import json2import numpy as np3import datetime4class NpEncoder(json.JSONEncoder):5 def default(self, obj):6 if isinstance(obj, np.integer):7 return int(obj)8 elif isinstance(obj, np.floating):9 return float(obj)10 elif isinstance(obj, np.ndarray):11 return obj.tolist()12 else:13 return super(NpEncoder, self).default(obj)14def filter_config(from_config, to_config): 15 """16 Exclude all except type: (dict, list, bool, int, loat, str)17 """18 if isinstance(from_config, dict):19 for key in list(from_config.keys()): 20 if isinstance(from_config[key], dict):21 to_config[key] = {} 22 to_config[key] = filter_config(from_config[key], to_config[key])23 if isinstance(from_config[key], list):24 to_config[key] = []25 to_config[key] = filter_config(from_config[key], to_config[key])26 if isinstance(from_config[key], bool):27 to_config[key] = from_config[key]28 if isinstance(from_config[key], int):29 to_config[key] = from_config[key]30 if isinstance(from_config[key], float):31 to_config[key] = from_config[key]32 if isinstance(from_config[key], str):33 to_config[key] = from_config[key]34 if isinstance(from_config, list):35 for value in from_config:36 if isinstance(value, dict):37 tmp_to_config = {}38 to_config.append(filter_config(value, tmp_to_config))39 if isinstance(value, list):40 tmp_to_config = []41 to_config.append(filter_config(value, tmp_to_config))42 if isinstance(value, bool):43 to_config.append(value)44 if isinstance(value, int):45 to_config.append(value)46 if isinstance(value, float):47 to_config.append(value)48 if isinstance(value, str):49 to_config.append(value)50 ...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful