Created
November 14, 2011 09:00
-
-
Save poochin/1363566 to your computer and use it in GitHub Desktop.
名前空間推測
This file contains hidden or 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
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| from inspect import currentframe | |
| import re | |
| class At: | |
| '''Namespace inference class | |
| ja: 名前空間推測クラス | |
| 推測文字列の規則 | |
| [( |.)(module|class|function)]( |.)function | |
| .: 前オブジェクトの子オブジェクトを示します | |
| (スペース): 前オブジェクトの子孫オブジェクトを示します | |
| (例) | |
| モジュール A 内のモジュール B 内の 関数 C を指定する場合 | |
| ".A.B.C" | |
| ".A C" | |
| " C" | |
| など。 | |
| ''' | |
| @staticmethod | |
| def isclassmodule(obj): | |
| if type(obj).__name__ in ('module', 'classobj'): | |
| return True | |
| return False | |
| @staticmethod | |
| def buildtree(contexts, recursion, path=""): | |
| if recursion <= 0: | |
| return [] | |
| found = [] | |
| for key, obj in contexts.iteritems(): | |
| newpath = '.'.join((path, key)) | |
| found.append((newpath, obj)) | |
| if At.isclassmodule(obj): | |
| found += At.buildtree(vars(obj), recursion=recursion-1, path=newpath) | |
| found.sort() | |
| return found | |
| def __init__(self, atpath, context=None, recursion=5, israsing=False): | |
| if At.isclassmodule(context): | |
| contexts = vars(context) | |
| elif not context: | |
| frame = currentframe().f_back | |
| contexts = frame.f_globals | |
| self.funcs = [] | |
| pattern = '^%s$' % atpath.replace('.', '\.').replace(' ', '(\.\w+)*\.') | |
| tree = self.buildtree(contexts, recursion=recursion) | |
| for key, obj in tree: | |
| if re.match(pattern, key): | |
| self.funcs.append(obj.__get__(0) | |
| if isinstance(obj, staticmethod) else obj) | |
| def __call__(self, *args): | |
| results = [] | |
| for f in self.funcs: | |
| if not callable(f): | |
| continue | |
| try: | |
| results.append(f(*args)) | |
| except TypeError: | |
| pass | |
| return results | |
| def helloworld(): | |
| return 'Hello, World!' | |
| if __name__ == '__main__': | |
| print At('.helloworld')() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment