Skip to content

Instantly share code, notes, and snippets.

@K-PTL
Forked from yoshipon/noglobal.py
Last active February 14, 2021 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save K-PTL/8c5cd27a963cec3fc32ad636d433fd77 to your computer and use it in GitHub Desktop.
Save K-PTL/8c5cd27a963cec3fc32ad636d433fd77 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 types
import inspect
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(fn):
fn_noglobal = types.FunctionType(fn.__code__, dict(imports()))
arg_info = inspect.getfullargspec(fn)
def wrapper(*wrapper_args, **wrapper_kwargs):
# both ways are work well in py3.8
# if arg_info.defaults is None:
# use_defaults = ()
# use_defaults += (None,)
# else:
# use_defaults = arg_info.defaults[::-1]
# kwargs = dict((k, v) for k, v in zip(arg_info.args[::-1], use_defaults))
if not arg_info.defaults is None:
kwargs = dict((k, v) for k, v in zip(arg_info.args[::-1], arg_info.defaults[::-1]))
else:
kwargs = dict()
for k, v in zip(arg_info.args, wrapper_args):
kwargs[k] = v
for k, v in wrapper_kwargs.items():
kwargs[k] = v
return fn_noglobal(**kwargs)
return wrapper
# usage example
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.arange(4)
# this var access shall break when called
#print(a)
print(b, c)
f(2)
@K-PTL
Copy link
Author

K-PTL commented Feb 14, 2021

Usually I use python3.7 and work @noglobal well. But, in case python3.8, I could not run it; faced TypeError because args.defaults is None.
Therefore, add the switching point if args.defaults is None or not.

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