def get_doc_object(obj, what=None, doc=None, config={}):
if what is None:
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
elif isinstance(obj, collections.Callable):
what = 'function'
else:
what = 'object'
if what == 'class':
return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc,
config=config)
elif what in ('function', 'method'):
return SphinxFunctionDoc(obj, doc=doc, config=config)
else:
if doc is None:
doc = pydoc.getdoc(obj)
return SphinxObjDoc(obj, doc, config=config)
python类ismodule()的实例源码
def __go(lcls):
global __all__
from .. import util as _sa_util
import inspect as _inspect
__all__ = sorted(name for name, obj in lcls.items()
if not (name.startswith('_') or _inspect.ismodule(obj)))
from .annotation import _prepare_annotations, Annotated
from .elements import AnnotatedColumnElement, ClauseList
from .selectable import AnnotatedFromClause
_prepare_annotations(ColumnElement, AnnotatedColumnElement)
_prepare_annotations(FromClause, AnnotatedFromClause)
_prepare_annotations(ClauseList, Annotated)
_sa_util.dependencies.resolve_all("sqlalchemy.sql")
from . import naming
def get_module(obj):
if inspect.ismodule(obj):
return obj
try:
obj = obj.__objclass__
except AttributeError:
pass
try:
imp_plz = obj.__module__
except AttributeError:
# Unfortunately in some cases like `int` there's no __module__
return builtins
else:
if imp_plz is None:
# Happens for example in `(_ for _ in []).send.__module__`.
return builtins
else:
try:
return __import__(imp_plz)
except ImportError:
# __module__ can be something arbitrary that doesn't exist.
return builtins
def _str_to_type_from_member_module(cls, module_, string):
"""
:type module_: module
:type string: str
:rtype: type
:raise: BunqException when could not find the class for the string.
"""
module_name_short, class_name = string.split(cls._DELIMITER_MODULE)
members = inspect.getmembers(module_, inspect.ismodule)
for name, module_member in members:
if module_name_short == name:
return getattr(module_member, class_name)
error_message = cls._ERROR_COULD_NOT_FIND_CLASS.format(string)
raise exception.BunqException(error_message)
def get_doc_object(obj, what=None, doc=None, config={}):
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
elif callable(obj):
what = 'function'
else:
what = 'object'
if what == 'class':
return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc,
config=config)
elif what in ('function', 'method'):
return SphinxFunctionDoc(obj, doc=doc, config=config)
else:
if doc is None:
doc = pydoc.getdoc(obj)
return SphinxObjDoc(obj, doc, config=config)
def test_excluding_predicates(self):
self.istest(inspect.isbuiltin, 'sys.exit')
if check_impl_detail():
self.istest(inspect.isbuiltin, '[].append')
self.istest(inspect.iscode, 'mod.spam.__code__')
self.istest(inspect.isframe, 'tb.tb_frame')
self.istest(inspect.isfunction, 'mod.spam')
self.istest(inspect.isfunction, 'mod.StupidGit.abuse')
self.istest(inspect.ismethod, 'git.argue')
self.istest(inspect.ismodule, 'mod')
self.istest(inspect.istraceback, 'tb')
self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory')
self.istest(inspect.isgenerator, '(x for x in range(2))')
self.istest(inspect.isgeneratorfunction, 'generator_function_example')
if hasattr(types, 'GetSetDescriptorType'):
self.istest(inspect.isgetsetdescriptor,
'type(tb.tb_frame).f_locals')
else:
self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
if hasattr(types, 'MemberDescriptorType'):
self.istest(inspect.ismemberdescriptor,
'type(lambda: None).__globals__')
else:
self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
renderer=None):
"""Render text documentation, given an object or a path to an object."""
if renderer is None:
renderer = text
object, name = resolve(thing, forceload)
desc = describe(object)
module = inspect.getmodule(object)
if name and '.' in name:
desc += ' in ' + name[:name.rfind('.')]
elif module and module is not object:
desc += ' in module ' + module.__name__
if not (inspect.ismodule(object) or
inspect.isclass(object) or
inspect.isroutine(object) or
inspect.isgetsetdescriptor(object) or
inspect.ismemberdescriptor(object) or
isinstance(object, property)):
# If the passed object is a piece of data or an instance,
# document its available methods instead of its value.
object = type(object)
desc += ' object'
return title % desc + '\n\n' + renderer.document(object, name)
def _normalize_module(module, depth=2):
"""
Return the module specified by `module`. In particular:
- If `module` is a module, then return module.
- If `module` is a string, then import and return the
module with that name.
- If `module` is None, then return the calling module.
The calling module is assumed to be the module of
the stack frame at the given depth in the call stack.
"""
if inspect.ismodule(module):
return module
elif isinstance(module, str):
return __import__(module, globals(), locals(), ["*"])
elif module is None:
return sys.modules[sys._getframe(depth).f_globals['__name__']]
else:
raise TypeError("Expected a module, string, or None")
def get_global_vars(func):
""" Store any methods or variables bound from the function's closure
Args:
func (function): function to inspect
Returns:
dict: mapping of variable names to globally bound VARIABLES
"""
closure = getclosurevars(func)
if closure['nonlocal']:
raise TypeError("Can't launch a job with closure variables: %s" %
closure['nonlocals'].keys())
globalvars = dict(modules={},
functions={},
vars={})
for name, value in closure['global'].items():
if inspect.ismodule(value): # TODO: deal FUNCTIONS from closure
globalvars['modules'][name] = value.__name__
elif inspect.isfunction(value) or inspect.ismethod(value):
globalvars['functions'][name] = value
else:
globalvars['vars'][name] = value
return globalvars
def annotations(memb):
"""Decorator applicable to functions, methods, properties,
classes or modules (by explicit call).
If applied on a module, memb must be a module or a module name contained in sys.modules.
See pytypes.set_global_annotations_decorator to apply this on all modules.
Methods with type comment will have type hints parsed from that
string and get them attached as __annotations__ attribute.
Methods with either a type comment or ordinary type annotations in
a stubfile will get that information attached as __annotations__
attribute (also a relevant use case in Python 3).
Behavior in case of collision with previously (manually)
attached __annotations__ can be controlled using the flags
pytypes.annotations_override_typestring and pytypes.annotations_from_typestring.
"""
if _check_as_func(memb):
return annotations_func(memb)
if isclass(memb):
return annotations_class(memb)
if ismodule(memb):
return annotations_module(memb)
if memb in sys.modules or memb in pytypes.typechecker._pending_modules:
return annotations_module(memb)
return memb
def auto_override(memb):
"""Decorator applicable to methods, classes or modules (by explicit call).
If applied on a module, memb must be a module or a module name contained in sys.modules.
See pytypes.set_global_auto_override_decorator to apply this on all modules.
Works like override decorator on type annotated methods that actually have a type
annotated parent method. Has no effect on methods that do not override anything.
In contrast to plain override decorator, auto_override can be applied easily on
every method in a class or module.
In contrast to explicit override decorator, auto_override is not suitable to detect
typos in spelling of a child method's name. It is only useful to assert compatibility
of type information (note that return type is contravariant).
Use pytypes.check_override_at_runtime and pytypes.check_override_at_class_definition_time
to control whether checks happen at class definition time or at "actual runtime".
"""
if type_util._check_as_func(memb):
return override(memb, True)
if isclass(memb):
return auto_override_class(memb)
if ismodule(memb):
return auto_override_module(memb, True)
if memb in sys.modules or memb in _pending_modules:
return auto_override_module(memb, True)
return memb
def _catch_up_global_typechecked_decorator():
mod_names = None
while mod_names is None:
try:
mod_names = [mn for mn in sys.modules]
except RuntimeError: # dictionary changed size during iteration
pass
for mod_name in mod_names:
if not mod_name in _fully_typechecked_modules:
try:
md = sys.modules[mod_name]
except KeyError:
md = None
if not md is None and ismodule(md):
typechecked_module(mod_name)
def __go(lcls):
global __all__
from .. import util as _sa_util
import inspect as _inspect
__all__ = sorted(name for name, obj in lcls.items()
if not (name.startswith('_') or _inspect.ismodule(obj)))
from .annotation import _prepare_annotations, Annotated
from .elements import AnnotatedColumnElement, ClauseList
from .selectable import AnnotatedFromClause
_prepare_annotations(ColumnElement, AnnotatedColumnElement)
_prepare_annotations(FromClause, AnnotatedFromClause)
_prepare_annotations(ClauseList, Annotated)
_sa_util.dependencies.resolve_all("sqlalchemy.sql")
from . import naming
def _normalize_module(module, depth=2):
"""
Return the module specified by `module`. In particular:
- If `module` is a module, then return module.
- If `module` is a string, then import and return the
module with that name.
- If `module` is None, then return the calling module.
The calling module is assumed to be the module of
the stack frame at the given depth in the call stack.
"""
if inspect.ismodule(module):
return module
elif isinstance(module, basestring):
return __import__(module, globals(), locals(), ["*"])
elif module is None:
return sys.modules[sys._getframe(depth).f_globals['__name__']]
else:
raise TypeError("Expected a module, string, or None")
def __init__(self, mod=None, globs=None, verbose=None,
isprivate=None, optionflags=0):
warnings.warn("class Tester is deprecated; "
"use class doctest.DocTestRunner instead",
DeprecationWarning, stacklevel=2)
if mod is None and globs is None:
raise TypeError("Tester.__init__: must specify mod or globs")
if mod is not None and not inspect.ismodule(mod):
raise TypeError("Tester.__init__: mod must be a module; %r" %
(mod,))
if globs is None:
globs = mod.__dict__
self.globs = globs
self.verbose = verbose
self.isprivate = isprivate
self.optionflags = optionflags
self.testfinder = DocTestFinder(_namefilter=isprivate)
self.testrunner = DocTestRunner(verbose=verbose,
optionflags=optionflags)
def __go(lcls):
global __all__
from .. import util as _sa_util
import inspect as _inspect
__all__ = sorted(name for name, obj in lcls.items()
if not (name.startswith('_') or _inspect.ismodule(obj)))
from .annotation import _prepare_annotations, Annotated
from .elements import AnnotatedColumnElement, ClauseList
from .selectable import AnnotatedFromClause
_prepare_annotations(ColumnElement, AnnotatedColumnElement)
_prepare_annotations(FromClause, AnnotatedFromClause)
_prepare_annotations(ClauseList, Annotated)
_sa_util.dependencies.resolve_all("sqlalchemy.sql")
from . import naming
def _pack_namespace(self):
"""Collect all the /pickable/ objects from the namespace
so to pass them to the async execution environment."""
white_ns = dict()
white_ns.setdefault('import_modules', list())
for k, v in self.shell.user_ns.items():
if not k in DEFAULT_BLACKLIST:
try:
if inspect_ismodule(v):
white_ns['import_modules'].append((k, v.__name__))
else:
_ = pickle_dumps({k: v})
white_ns[k] = v
except PicklingError:
continue
except Exception:
continue
white_ns['connection_id'] = self.connection_id
return white_ns
def generate_rest_files(module,path='source'):
import fandango
print '\n'*5
print 'Writing documentation settings to %s/*rst' % (path)
if fandango.isString(module): module = fandango.loadModule(module)
submodules = [(o,v) for o,v in vars(module).items()
if inspect.ismodule(v) and v.__name__.startswith(module.__name__)]
for o,v in submodules:
filename = path+'/'+o+'.rst'
if not os.path.isfile(filename):
print('writing %s'%filename)
open(filename,'w').write(DEFAULT_MODULE%(v.__name__,'='*len(v.__name__),v.__name__))
print('\nWrite this into index.rst:\n')
print("""
.. toctree::
:maxdepth: 2
"""+
'\n '.join([t[0] for t in submodules]))
def get_doc_object(obj, what=None, config=None):
if what is None:
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
elif callable(obj):
what = 'function'
else:
what = 'object'
if what == 'class':
doc = SphinxTraitsDoc(obj, '', func_doc=SphinxFunctionDoc, config=config)
if looks_like_issubclass(obj, 'HasTraits'):
for name, trait, comment in comment_eater.get_class_traits(obj):
# Exclude private traits.
if not name.startswith('_'):
doc['Traits'].append((name, trait, comment.splitlines()))
return doc
elif what in ('function', 'method'):
return SphinxFunctionDoc(obj, '', config=config)
else:
return SphinxDocString(pydoc.getdoc(obj), config=config)
def get_doc_object(obj, what=None, doc=None, config={}):
if what is None:
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
elif callable(obj):
what = 'function'
else:
what = 'object'
if what == 'class':
return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc,
config=config)
elif what in ('function', 'method'):
return SphinxFunctionDoc(obj, doc=doc, config=config)
else:
if doc is None:
doc = pydoc.getdoc(obj)
return SphinxObjDoc(obj, doc, config=config)