title: Create own version of Optional
body: <p>I have something like this in my code:</p>
  
  <pre class="lang-py prettyprint-override"><code>Undefined = Literal['__undefined_attr__']
  undefined: Undefined = '__undefined_attr__'
  
  def funkc(
      foo: Union[str, Undefined] = undefined,
      bar: Union[int, Undefined] = undefined,
      baz: Union[str, Undefined] = undefined,
      boo: Union[float, Undefined] = undefined,
      # ... lots more args like that with many different types
  ):
      if foo is not undefined:
          ...
      if bar is not undefined:
          ...
      ...  # etc.
  </code></pre>
  
  <p>Now, if I could use None as the default value, this would all get much simpler, like:</p>
  
  <pre class="lang-py prettyprint-override"><code>def funkc(
      foo: Optional[str] = None,
      bar: Optional[int] = None,
      baz: Optional[str] = None,
      boo: Optional[float] = None,
      # ... lots more args like that with many different types
  ):
      if foo is not None:
          ...
      if bar is not None:
          ...
      ...  # etc.
  </code></pre>
  
  <p>So I was thinking I could create my own type shortcut, which could be used like:</p>
  
  <pre class="lang-py prettyprint-override"><code>def funkc(
      foo: OptionallyDefined[str] = undefined,
      bar: OptionallyDefined[int] = undefined,
      baz: OptionallyDefined[str] = undefined,
      boo: OptionallyDefined[float] = undefined,
      # ... lots more args like that with many different types
  ):
      if foo is not undefined:
          ...
      if bar is not undefined:
          ...
      ...  # etc.
  </code></pre>
  
  <p>But actually creating this <code>OptionalylDefined</code> thing is escaping me. Is this possible with mypy?</p>
  
  <hr>
  
  <p><strong>Solution:</strong></p>
  
  <p>Thanks to <a href="https://stackoverflow.com/a/59303785/236195">user2357112 supports Monica's answer</a>, this it what I'm using in the end:</p>
  
  <pre class="lang-py prettyprint-override"><code>class Undefined:
      instance = None
  
      def __new__(cls, *args, **kwargs) -&gt; "Undefined":
          """Singleton, just in case..."""
          if not cls.instance:
              cls.instance = super().__new__(cls, *args, **kwargs)  # type: ignore
          return cls.instance
  
  
  undefined = Undefined()
  ArgType = TypeVar("ArgType")
  OptionallyDefined = Union[ArgType, Undefined]
  
  
  def funkc(...):
      if foo is not undefined:
          ...
  </code></pre>