From d08248f6aa368212d76e6c5393163d747f28602d Mon Sep 17 00:00:00 2001 From: Andy Kipp Date: Fri, 12 Jul 2024 02:21:21 +0200 Subject: [PATCH] builtin: added ``__xonsh__.imp`` to have an ability to import and use modules immediately in one line (#5595) * imp * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * imp * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * imp * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: a <1@1.1> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- news/inline_import.rst | 25 +++++++++++++++++++++++++ xonsh/built_ins.py | 10 ++++++++++ 2 files changed, 35 insertions(+) create mode 100644 news/inline_import.rst diff --git a/news/inline_import.rst b/news/inline_import.rst new file mode 100644 index 000000000..89de8731c --- /dev/null +++ b/news/inline_import.rst @@ -0,0 +1,25 @@ +**Added:** + +* builtin: added ``__xonsh__.imp`` to have an ability to import and use modules immediately in one line + e.g. ``__xonsh__.json.loads('{}')``. + In the future ``__xonsh__`` will have short notation ``@`` and the line will looks more elegant ``@.imp.json.loads('{}')``. + +**Changed:** + +* + +**Deprecated:** + +* + +**Removed:** + +* + +**Fixed:** + +* + +**Security:** + +* diff --git a/xonsh/built_ins.py b/xonsh/built_ins.py index 4a9262a90..24c18b9d2 100644 --- a/xonsh/built_ins.py +++ b/xonsh/built_ins.py @@ -520,6 +520,15 @@ def xonsh_builtins(execer=None): XSH.unload() +class InlineImporter: + """Inline importer allows to import and use module attribute or function in one line.""" + + def __getattr__(self, name): + if name.startswith("__"): + return getattr(super(), name) + return __import__(name) + + class XonshSession: """All components defining a xonsh session.""" @@ -530,6 +539,7 @@ class XonshSession: self.history = None self.shell = None self.env = None + self.imp = InlineImporter() self.rc_files = None # AST-invoked functions