I am having trouble dealing with classes wherein I have classes whose attributes and methods I want to access in my API code, but not have those attributes and methods exposed to the user who is using the API.
Consider this code example:
class Context:
pass
class Foo(Generic[T]):
_context: Context
class Bar(Generic[T]):
_context: Context
def func_1(foo: Foo[str]) -> int:
# do something with _context
return NotImplemented
def func_2(foo: Foo[int], bar: Bar[int]) -> Bar[str]:
# do something with _context
return NotImplemented
The two functions are like operators that act on these objects, and it doesn't make sense to have them as methods to Foo and Bar in my application. Additionally they only act on certain types of the Foo and Bar classes. If I access foo._context inside func_1 for example, mypy and pylance will yell at me due to accessing a private attribute. But I don't want to make it public since I don't want the users of the API to access this function. How can I overcome this while still keeping my code up to typing standards?
I understand that a simple way would be to simply access foo._context inside the functions and include a typing ignore comment. However, this doesn't seem clean to me and I was wondering if there was a Pythonic way to do this. Along the same lines as this question, I was wondering if there was a way to prevent the users of an API from instantiating a public class, but still instantiate somehow within the API. I mean that these class attributes and methods should be public inside the package for developers but not for library users.
# type: ignoretherefore shouldn't suppress anything._contextmeans "implementation-specific" more than it means "private". Developers are by definition working on the implementation, so they are free to access it, while ordinary users are not.