Skip to content

Instantly share code, notes, and snippets.

@GrahamDumpleton
Last active August 29, 2015 14:23
Show Gist options
  • Save GrahamDumpleton/6be06d259a166d69bf8c to your computer and use it in GitHub Desktop.
Save GrahamDumpleton/6be06d259a166d69bf8c to your computer and use it in GitHub Desktop.
Exporting functions and variables from a module.
# exports.py
import sys
class Exports(object):
def __getattr__(self, name):
context = sys._getframe().f_back.f_globals
return context[name]
def __setattr__(self, name, value):
context = sys._getframe().f_back.f_globals
context[name] = value
exported = context.setdefault('__all__', [])
if name not in exported:
exported.append(name)
def __call__(self):
return sys._getframe().f_back.f_globals
exports = Exports()
def export(wrapped):
context = sys._getframe().f_back.f_globals
exported = context.setdefault('__all__', [])
name = wrapped.__name__
if name not in exported:
exported.append(name)
return wrapped
# check.py
from exports import exports, export
exports.VARNAME = 'VALUE'
@export
def func():
return VARNAME
print __all__
print exports()
# test
$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from check import *
['VARNAME', 'func']
['VARNAME', 'func']
>>> print VARNAME
VALUE
>>> func()
'VALUE'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment