Hello everyone, I'm trying to define my custom blo...
# prefect-community
m
Hello everyone, I'm trying to define my custom block as a PoC, however, i am not able to access it using the snippet given in Prefect UI after registering the Block. I tried importing it using
Copy code
from prefect.blocks.core import Block 
cube = Block.load('Cube/cube-test')
where Cube is the name of the registered block and cube-test is an instance of it. i would always get
ValueError: Unable to find block document named cube-test for block type Cube
I ran this code to find all the registered blocks
Copy code
from prefect.utilities.dispatch import lookup_type, get_registry_for_type
from prefect.blocks.core import Block
registry = get_registry_for_type(Block)
print(registry)
And it results in all the default prefect block without my custom blocks Am I missing something? Thanks in advance
1
j
Hi Mohamed. To make sure I understand: You see the block type (cube) you created in the GUI and created a block in the GUI from that block type. But then you aren’t able to use the block in your code. is that correct? Assuming that’s correct: If you run
prefect block ls
does the block you created appear? If not, check that the profile that you using in your terminal matches where you created your block.
m
Hello Jeff, thanks for your speedy answer. When i run the
prefect block ls
command i do see the blocks i created. The question is how do i access them in my code?
j
Hi @Mohamed Alaa, we will make how to access blocks of a custom block type more clear. At the moment, the following should work (I just tested it): Put this code in a Python file and run it to create a custom block type and block:
Copy code
# create custom block example
from prefect.blocks.core import Block


class Cube3(Block):
    edge_length_inches: float

    def get_volume(self):
        return self.edge_length_inches**3

    def get_surface_area(self):
        return 6 * self.edge_length_inches**2


if __name__ == "__main__":
    my_cube_object = Cube3(edge_length_inches=3)
    my_cube_object.save(name="cubeit3")
Use the custom block in another file at the same directory level:
Copy code
from prefect import flow
from customblock import Cube3


@flow
def testing():
    cube_block = Cube3.load("cubeit3")
    print(cube_block)


if __name__ == "__main__":
    testing()
Note that here you are importing the class from the other file, so that file needs to be accessible.
m
it worked! thanks a lot jeff
👍 1