I have a class function that I only want to define if a certain module (X), defined as an installation "extra" is available. class ABC: try: from X import y def to_y(self) -> ???: return self.y(self) except ImportError: pass The problem here is that y is now tied to the scope of the class rather than the global scoping that type hints seem to need. How do I get around this? Obviously I could take all this outside the class scope and monkey patch in the to_y method. Or I could make a global variable which is None when X is not available and use that. I'm curious if there's a better, more obvious way to achieve this. Continue reading...