<@ULVA73B9P>, Is there a method/way to directly in...
# ask-marvin
m
@Marvin, Is there a method/way to directly instantiate a block, such as an AwsCredentials Block withouth importing the class AwsCredentials from prefect_aws? In my code, I obtain block information from a data class, which looks like this: Model( name='wamapi-aws-credentials', class_name='AwsCredentials', params={'aws_access_key_id': '*****', 'aws_secret_access_key': '*****', 'region_name': 'eu-west-1'}, tag=None, type='block' ) From this, I would like to instantiate the block. Currently, I use _globals()[class_name](name=model.name, **model.params)_, but this requires me to import each block into the script. Since this script will deploy blocks for our customers, I want to avoid having to import every type of block that I might use for different customers. Is there a way to achieve this?
m
Based on the information available, it seems that you need to register the blocks in Prefect-AWS with the command
prefect block register -m prefect_aws
after installing the Prefect-AWS library. However, the documents do not provide a direct method to instantiate a block such as an AwsCredentials Block without importing the class AwsCredentials from prefect_aws. The common practice in Python to dynamically instantiate a class involves importing the class, as you're currently doing with
_globals()<name=model.name, **model.params|class_name>
. Avoiding this would likely require a different approach or design. I would recommend reaching out to the Prefect community or support for more specific guidance on this issue.
k
@MarcoM is your goal here to instantiate and then use block methods other than
save()
, or is this meant to be an interface just for saving blocks?
m
@Kevin Grismore my goal is to instantiate the block and then save it. The provided code snippet demonstrates how I deploy models by first loading the model object, and then saving it. Specifically, in the load_model_obj method, I dynamically create an instance of a block but we need to import every type of block explicitly.
Copy code
def deploy(self, models: Union[Model, list[Model]]) -> None:
    models = [models] if not isinstance(models, list) else models
    for model in models:
        model_name = model.name
        model_obj = self.load_model_obj(model)
        model_obj.save(name=model_name, overwrite=True)

def load_model_obj(self, model: Model) -> Block:
    class_name = model.class_name
    for param_name, param_value in model.params.items():
        model.params[param_name] = self.expand_param_value(param_value)
    model_obj = globals()[class_name](name=model.name, **model.params)#!!!capire come gestire questa cosa, al momento importiamo
    return model_obj