Checking and modifying a record that was initialized as 'None'

When you want to modify a record in the storage conditionally, how would you do it?
Especially if it was initialized as ‘None’ value.

As per smartpy manual you could check optional values with is_none() or is_some() but it seems not to be that straight forward with records initialized with ‘None’ value.

for example

def __init__(self):
    self.data.x = sp.cast(None, sp.option[sp.record(a=sp.nat)])

@sp.entrypoint
def entry(self, z):
    sp.cast(z, sp.nat)
    if self.data.x.is_none():
        y = z
    else: 
        y = self.data.x.a + z

    self.data.x = sp.Some(sp.record(a=y))

The example I gave above does not work.

Online IDE gave

"
self.data.x: sp.option(sp.record(a=sp.nat)) has no field ‘a’ of type sp.unknown
Expected type ‘TRecord++(a=sp.unknown)’ but got ‘sp.option(sp.record(a=sp.nat)’
"

You can use unwrap_some.

It returns a value from an option of a value. It raises an error if the option is None.

def __init__(self):
    self.data.x = sp.cast(None, sp.option[sp.record(a=sp.nat)])

@sp.entrypoint
def entry(self, z):
    sp.cast(z, sp.nat)
    if self.data.x.is_none():
        y = z
    else: 
        y = self.data.x.unwrap_some().a + z

    self.data.x = sp.Some(sp.record(a=y))

Just to add the result of our discussion here as well.

regards to my example, it will not work.
“error: Variable ‘y’ is not defined”

Jordan: “That’s a scope problem. In most languages you cannot get access to a variable defined inside a bloc outside of it. In python you can.”

def __init__(self):
    self.data.x = sp.cast(None, sp.option[sp.record(a=sp.nat)])

@sp.entrypoint
def entry(self, z):
    y = 0  # <---
    if self.data.x.is_none():
        y = z
    else: 
        y = self.data.x.unwrap_some().a + z

    self.data.x = sp.Some(sp.record(a=y))

The issue is that in my initial example, I declared the variable the first time inside the if-else block. This time I declared it (with a 0 value) before the block, and proceeded to make the changes as I wanted to.