1

I am trying to emulate the idea of ok and err variants from rust in python, here is a result class

from typing import Any, Union

class Result:
    def __init__(self, value: Any, status: bool = True) -> None:
        self.value = value
        self.status = status

    @classmethod
    def Ok(cls, result: Any) -> Result:
        return cls(result, status=True)

    @classmethod
    def Err(cls, error: Any):
        return cls(error, status=False)

    def unwrap(self):
        if self.status:
            print("from Result -> self.status TRUE")
            print(f"from Result -> self.value = {self.value}")
            return self.value
        else:
            print("from Result -> self.status FALSE")
            print(f"from Result -> self.value = {self.value}")
            return self.value

I cannot just use the class name Result to indicate the return type, how do can I properly do so using the typing module or with whatever other method that is available? TY!

EDIT:

would i so something like

    @classmethod
    def ok(cls, result: Any) -> __init__:
        return cls(result, status=True)
userh897
  • 73
  • 7
  • _"I cannot just use the class name Result to indicate the return type"_, You actually can! Use `"Result"`, or add `from __future__ import annotations` to the top of your module. See the dupe target for the details. – Brian61354270 Apr 03 '23 at 15:09
  • Isn't putting Result in quotes just indicating it's a String – userh897 Apr 03 '23 at 15:11
  • 1
    No, typing tools will resolve this string in context to an actual class. You'd need to use `typing.Literal` to indicate that you're literally returning a string. – deceze Apr 03 '23 at 15:12
  • 1
    The `Self` type annotation has been introduced by PEP 673 for this purpose. It avoids you having to change anything on class getting renamed. – PoneyUHC Apr 03 '23 at 15:12

0 Answers0