diff options
-rw-r--r-- | ChangeLog | 4 | ||||
-rw-r--r-- | astroid/manager.py | 7 | ||||
-rw-r--r-- | tests/unittest_manager.py | 11 |
3 files changed, 22 insertions, 0 deletions
@@ -6,6 +6,10 @@ What's New in astroid 2.4.0? ============================ Release Date: TBA +* Expose a ast_from_string method in AstroidManager, which will accept + source code as a string and return the corresponding astroid object + + Closes PyCQA/astroid#725 * Infer qualified ``classmethod`` as a classmethod. Close PyCQA/pylint#3417 diff --git a/astroid/manager.py b/astroid/manager.py index 5e25e6e2..4e1452ef 100644 --- a/astroid/manager.py +++ b/astroid/manager.py @@ -99,6 +99,13 @@ class AstroidManager: "Unable to build an AST for {path}.", path=filepath ) + def ast_from_string(self, data, modname="", filepath=None): + """ Given some source code as a string, return its corresponding astroid object""" + # pylint: disable=import-outside-toplevel; circular import + from astroid.builder import AstroidBuilder + + return AstroidBuilder(self).string_build(data, modname, filepath) + def _build_stub_module(self, modname): # pylint: disable=import-outside-toplevel; circular import from astroid.builder import AstroidBuilder diff --git a/tests/unittest_manager.py b/tests/unittest_manager.py index b56a0580..f22414c4 100644 --- a/tests/unittest_manager.py +++ b/tests/unittest_manager.py @@ -67,6 +67,17 @@ class AstroidManagerTest( exceptions.AstroidBuildingError, self.manager.ast_from_file, "unhandledName" ) + def test_ast_from_string(self): + filepath = unittest.__file__ + dirname = os.path.dirname(filepath) + modname = os.path.basename(dirname) + with open(filepath, "r") as file: + data = file.read() + ast = self.manager.ast_from_string(data, modname, filepath) + self.assertEqual(ast.name, "unittest") + self.assertEqual(ast.file, filepath) + self.assertIn("unittest", self.manager.astroid_cache) + def test_do_not_expose_main(self): obj = self.manager.ast_from_module_name("__main__") self.assertEqual(obj.name, "__main__") |