kcl icon indicating copy to clipboard operation
kcl copied to clipboard

Is there an equivalent of isinstance() of python

Open wonderyl opened this issue 1 year ago • 1 comments

General Question

I'm trying to write a function that behaves differently based on the type of the schemas. E.g.

schema Parent:
  a: int

schema Child(Parent):
  b: int

schema GrandChild(Child):
  b = 2

schema foo[s: any]:
  output: int

  if isinstance(s, Child):
    output = s.b
  else:
    output = s.a

bar = foo(GrandChild{})

The build in typeof() function doesn't work because it doesn't expose inheritance chain.

Any suggested would be appreciated.

wonderyl avatar Aug 25 '25 04:08 wonderyl

Closing — KCL doesn't have an isinstance builtin. For the parent/child schema check you described, the most common workaround is duck-typing: try to access an attribute that exists on the child and fall back to the parent attribute:

schema Parent:
    a: int

schema Child(Parent):
    b: int

schema foo[s: any]:
    output: int

    if s.b \!= Undefined:    # Child has `b`
        output = s.b
    else:
        output = s.a

If you really need explicit type checks (e.g. for schema unions from config), file a separate enhancement issue — KCL's is_fit_schema runtime check exists internally but is not exposed as a builtin today.

Peefy avatar Aug 29 '26 17:08 Peefy