Created
December 1, 2022 20:57
-
-
Save alexandru-dinu/3572d6dc229b3ca86ea8fdbc3689a5a2 to your computer and use it in GitHub Desktop.
IPython magic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from IPython.core.magic import register_line_magic | |
# From https://stackoverflow.com/a/64791087 | |
def _global_import(obj: str, syn: str = None, ctx: str = None): | |
"""[from `ctx`] import `obj` [as `syn`]""" | |
explain = [f"import {obj}"] | |
if syn: | |
explain.append(f"as {syn}") | |
if ctx: | |
explain.insert(0, f"from {ctx}") | |
print(" ".join(explain)) | |
if not syn: | |
syn = obj | |
if not ctx: | |
globals()[syn] = __import__(obj) | |
else: | |
globals()[syn] = getattr(__import__(ctx, fromlist=[obj]), obj) | |
@register_line_magic | |
def magic_import_common(line): | |
_global_import("Path", None, "pathlib") | |
_global_import("numpy", "np") | |
_global_import("torch", "T") | |
_global_import("nn", "nn", "torch") | |
_global_import("pandas", "pd") | |
_global_import("pyplot", "plt", "matplotlib") | |
_global_import("seaborn", "sns") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment