Skip to content

Instantly share code, notes, and snippets.

@raven38
Forked from yoshipon/noglobal.py
Created December 6, 2020 08:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save raven38/4e4c3c7a179283c441f575d6e375510c to your computer and use it in GitHub Desktop.
Save raven38/4e4c3c7a179283c441f575d6e375510c to your computer and use it in GitHub Desktop.
Useful Noglobal in Python
# License:
# I hereby state this snippet is below "threshold of originality" where applicable (public domain).
#
# Otherwise, since initially posted on Stackoverflow, use as:
# CC-BY-SA 3.0 skyking, Glenn Maynard, Axel Huebl
# http://stackoverflow.com/a/31047259/2719194
# http://stackoverflow.com/a/4858123/2719194
import builtins
import types
def imports():
for name, val in globals().items():
# module imports
if isinstance(val, types.ModuleType):
yield name, val
# functions / callables
if hasattr(val, '__call__'):
yield name, val
def noglobal(f):
return types.FunctionType(f.__code__,
dict(imports()),
f.__name__,
f.__defaults__,
f.__closure__
)
import numpy as np
import matplotlib.pyplot as plt
import h5py
a = 1
@noglobal
def f(b, c=1):
h5py.is_hdf5("a.tmp")
# only np. shall be known, not numpy.
np.arange(4)
# numpy.arrange(4)
# this var access shall break when called
# print(a)
print(b, c)
f(2)
@bilzard
Copy link

bilzard commented Nov 19, 2022

Thank you for sharing this code.
I made noglobal package from this snippet, and published to PyPI.
You seems to hold CC-BY-SA 3.0 license to this snippet, but the FAQ page1 says creative commons license is not suitable to software. So I published this package with MIT license, and name you in attribution section on README.
If you mind this, please let me know.

Footnotes

  1. https://creativecommons.org/faq/#can-i-apply-a-creative-commons-license-to-software

@raven38
Copy link
Author

raven38 commented Nov 28, 2022

LGTM

@bilzard
Copy link

bilzard commented Nov 28, 2022

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment