title: Python typing: how to declare a variable that is either a path-like object (os.path) or a Path (pathlib)
body: <p>I understand that module pathlib is new since Python 3.4 and I'm trying to use it as much as possible, but I have a lot of existing code with: &quot;import os.path&quot;. I'm also trying to add typing to my code since a few weeks, but I'm still learning how to do it. I don't understand yet how to declare a variable with an ambiguous type - casu quo a variable which is either a so-called path-like object (os.path) or a Path (pathlib). Such a variable could then be used as input for e.g. an open statement. I tried this in a test module called test_typevar:</p>
  <pre><code>from pathlib import Path
  from typing import TypeVar
  from some_module import some_function
  
  PathLike = TypeVar(&quot;PathLike&quot;, str, Path)
  fpath: PathLike
  line: str
  
  # Now suppose fpath is returned by some code and it's either a Path or a path-like object:
  fpath = some_function()
  with open(fpath, &quot;rt&quot;) as f:
      line = f.readline()
      ...
  </code></pre>
  <p>This is the error statement I'm getting:<br>
  error: Type variable &quot;test_typevar.PathLike&quot; is unbound<br>
  note: (Hint: Use &quot;Generic[PathLike]&quot; or &quot;Protocol[PathLike]&quot; base class to bind &quot;PathLike&quot; inside a class)<br>
  note: (Hint: Use &quot;PathLike&quot; in function signature to bind &quot;PathLike&quot; inside a function)</p>
  <p>Can anybody explain things further?</p>