If I keep that type annotation I get warnings further on in my code. Testing shows that type(data) is bytes and type(path) is str. However if I change to:
You get warnings if you change the type annotations since you violated the Liskov substitution principle. But what warnings did you originally get exactly?
The warnings are actually pretty straightforward. The first one is because you’re trying to make a BytesIO but the constructor only accepts objects implementing the buffer protocol, whereas you’re directly passing the argument through (maybe you should handle the cases where the argument takes those types; I suggest you start with reading the docs). If you convert the path to string using os.fsdecode and then normalize it using pathlib.Path.resolve, the subsequent errors should go away.
I’m confused. Did you declare the type of your data and path variables when you created them?
Because the only way the type checker would think that data is of type Buffer | str | Module | Expression | Interactive is if you failed to give it any more specific information. If you know data is bytes and path is str, then declare them as such. Otherwise, what’s the point in using a type checker?
If you don’t know the types of bytes and str, then the type checker is giving you a valid warning - not all values for data that can be passed to source_to_code are suitable for passing to your func2, so you need to fix that problem (possibly the way @jonathandung suggests).
OK, I think I get what you’re asking now. You’re implementing source_to_code and calling your func2 from within that implementation? My apologies, that wasn’t clear from your original post.
In that case, you have to be prepared for any type supported by the annotation. At the moment you aren’t, because you’re passing data to BytesIO, which can only accept objects of type Buffer (as the warning says). You need to decide what to do if you get passed a str, a Module, an Expression or an Interactive.
Maybe the answer is to do a runtime type check and raise an exception when passed something that isn’t a Buffer. Maybe you need to work out when source_to_code can be called with one of those other types, and work out how to handle those cases. Only you can decide what your code should do.
What you shouldn’t do is try to hack the type annotations so that they don’t report issues. The whole point of using a type checker is to detect problems such as these, so if you don’t want to deal with the issues, just don’t run the type checker (or suppress it with # type: ignore).
You can just use a normal isinstance() call. if not isinstance(data, Buffer): raise TypeError will “narrow” the type of data in the type checker’s eyes.
Dunc’s solution would only work if you’re sure the loader won’t be passed non-buffer data. Have you tried adding a print in the method to see what types you get?