From 3b62ca88e4217679e4291126162252e75396fb10 Mon Sep 17 00:00:00 2001 From: Brett Cannon Date: Mon, 27 May 2013 21:11:04 -0400 Subject: Issue #18072: Implement get_code() for importlib.abc.InspectLoader and ExecutionLoader. --- Lib/importlib/abc.py | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) (limited to 'Lib/importlib/abc.py') diff --git a/Lib/importlib/abc.py b/Lib/importlib/abc.py index cdcf244d38..b45e7d6572 100644 --- a/Lib/importlib/abc.py +++ b/Lib/importlib/abc.py @@ -147,14 +147,18 @@ class InspectLoader(Loader): """ raise ImportError - @abc.abstractmethod def get_code(self, fullname): - """Abstract method which when implemented should return the code object - for the module. The fullname is a str. Returns a types.CodeType. + """Method which returns the code object for the module. - Raises ImportError if the module cannot be found. + The fullname is a str. Returns a types.CodeType if possible, else + returns None if a code object does not make sense + (e.g. built-in module). Raises ImportError if the module cannot be + found. """ - raise ImportError + source = self.get_source(fullname) + if source is None: + return None + return self.source_to_code(source) @abc.abstractmethod def get_source(self, fullname): @@ -194,6 +198,22 @@ class ExecutionLoader(InspectLoader): """ raise ImportError + def get_code(self, fullname): + """Method to return the code object for fullname. + + Should return None if not applicable (e.g. built-in module). + Raise ImportError if the module cannot be found. + """ + source = self.get_source(fullname) + if source is None: + return None + try: + path = self.get_filename(fullname) + except ImportError: + return self.source_to_code(source) + else: + return self.source_to_code(source, path) + class FileLoader(_bootstrap.FileLoader, ResourceLoader, ExecutionLoader): -- cgit v1.2.1