-
Notifications
You must be signed in to change notification settings - Fork 4
/
stubs.py
executable file
·1956 lines (1715 loc) · 77.8 KB
/
stubs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from pydoc import * #@UnusedWildImport
import pydoc, sys, pprint #@Reimport
import __builtin__
import os #@Reimport
import pkgutil #@Reimport
import collections
import inspect
import ast
import keyword
import re
import types
import json
OBJ = 0
OBJTYPE = 1
SOURCEMOD = 2
NAMES = 3
PYTHON_OBJECT_RE = re.compile(
'^[a-zA-Z_][a-zA-Z_0-9]*(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*(?:\(.*\))?$')
builtins = set(__builtin__.__dict__.values())
# some basic data types which may not exist...
if 'bytes' not in globals():
bytes = str
if 'basestring' not in globals():
basestring = str
verbose = False
# def classify_class_attrs(object):
# """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
# def fixup(data):
# name, kind, cls, value = data
# if inspect.isdatadescriptor(value):
# if kind == 'property':
# print name, value, cls
# kind = 'data descriptor'
# return name, kind, cls, value
# return map(fixup, inspect.classify_class_attrs(object))
def walk_packages(path=None, prefix='', onerror=None, skip_regex=None):
"""Yields (module_loader, name, ispkg) for all modules recursively
on path, or, if path is None, all accessible modules.
'path' should be either None or a list of paths to look for
modules in.
'prefix' is a string to output on the front of every module name
on output.
Note that this function must import all *packages* (NOT all
modules!) on the given path, in order to access the __path__
attribute to find submodules.
'onerror' is a function which gets called with one argument (the
name of the package which was being imported) if any exception
occurs while trying to import a package. If no onerror function is
supplied, ImportErrors are caught and ignored, while all other
exceptions are propagated, terminating the search.
Examples:
# list all modules python can access
walk_packages()
# list all submodules of ctypes
walk_packages(ctypes.__path__, ctypes.__name__+'.')
"""
def seen(p, m={}):
if p in m:
return True
m[p] = True
for importer, name, ispkg in pkgutil.iter_modules(path, prefix):
if skip_regex and re.match(skip_regex, name):
if verbose:
print("skipping %s %s" % (name, skip_regex))
continue
yield importer, name, ispkg
if ispkg:
try:
mod = __import__(name)
except ImportError:
if onerror is not None:
onerror(name)
except Exception:
if onerror is not None:
onerror(name)
else:
raise
else:
path = getattr(sys.modules[name], '__path__', None) or []
# don't traverse path items we've seen before
path = [p for p in path if not seen(p)]
for item in walk_packages(path, name+'.', onerror, skip_regex):
yield item
def subpackages(packagemod, skip_regex=None):
"""
Given a module object, returns an iterator which yields a tuple
(modulename, moduleobject, ispkg)
for the given module and all it's submodules/subpackages.
"""
if hasattr(packagemod, '__path__'):
yield packagemod.__name__, packagemod, True
for importer, modname, ispkg in walk_packages(
packagemod.__path__, packagemod.__name__ + '.',
skip_regex=skip_regex):
# if skip_regex and re.match(skip_regex, modname):
# print("skipping %s %s" % (modname, skip_regex))
# mod = None
# else:
if modname not in sys.modules:
if verbose:
print("importing %s" % (modname,))
try:
mod = importer.find_module(modname).load_module(modname)
except Exception, e:
print "error importing %s: %s" % (modname, e)
mod = None
else:
mod = sys.modules[modname]
yield modname, mod, ispkg
else:
yield packagemod.__name__, packagemod, False
def get_source_module(obj, default):
mod = inspect.getmodule(obj)
if mod == __builtin__ and obj in builtins:
return mod
if (not mod or inspect.isbuiltin(obj) or isdata(obj)
or not mod.__name__ or mod.__name__.startswith('_')):
mod = default
return mod
def get_unique_name(basename=None, all_names=()):
if basename is None:
basename = '_unknown'
elif not basename.startswith('_'):
# we only use this in cases where the name wasn't orignally
# found in the module - ie, we're just trying to add in
# something that isn't really supposed to be in the module, but
# we need it there to refer to it...
# ...therefore, we want to make sure the name is at least
# hidden...
basename = '_' + basename
name = basename
num = 2
while name in all_names:
name = '%s%s' % (basename, num)
num += 1
return name
def get_class(obj):
'''Retrieves the class of the given object.
unfortunately, it seems there's no single way to query class that works in
all cases - `.__class__` doesn't work on some builtin-types, like
`re._pattern_type` instances, and type() doesn't work on old-style
classes...
'''
cls = type(obj)
if cls is types.InstanceType:
cls = obj.__class__
return cls
def has_default_constructor(cls):
'''Returns true if it's possible to make an instance of the class with no args.
'''
# these classes's __init__/__new__ are slot_wrapper objects, which we can't
# query... but we know that they are ok...
if is_named_tuple(cls):
return False
safe_methods = set()
for safe_cls in (object, list, dict, tuple, set, frozenset, str, unicode):
safe_methods.add(safe_cls.__init__)
safe_methods.add(safe_cls.__new__)
for method in (getattr(cls, '__init__', None),
getattr(cls, '__new__', None)):
if method in safe_methods:
continue
if method is None:
# we got an old-style class that didn't define an __init__ or
# __new__... it's ok..
continue
try:
args, _, _, defaults = inspect.getargspec(method)
except TypeError:
# sometimes we get 'slot_wrapper' objects, which we can't query...
# assume these are bad...
return False
if defaults is None:
numDefaults = 0
else:
numDefaults = len(defaults)
# there can be one 'mandatory' arg - which will be cls or self
if len(args) > numDefaults + 1:
return False
return True
def is_dict_like(obj):
'''Test whether the object is "similar" to a dict
'''
if isinstance(obj, collections.Mapping):
return True
for method in ('__getitem__', '__setitem__', 'keys'):
if not inspect.ismethod(getattr(obj, method, None)):
return False
return True
def is_named_tuple(cls):
'''Detect whether we think a class is the result of a namedtuple call'''
if not inspect.isclass(cls):
raise ValueError('is_named_tuple must be passed class objects - got '
'{!r}'.format(cls))
if not isinstance(cls, type):
# print "old-style class"
return False
if cls.__bases__ != (tuple,):
# print "wrong bases"
return False
if cls.__dict__.get('__slots__') != ():
# print "no slots"
return False
fields = cls.__dict__.get('_fields')
if not isinstance(fields, tuple):
# print "no fields"
return False
if not all(isinstance(f, basestring) for f in fields):
# print "non-string fields"
return False
if not isinstance(cls.__dict__.get('_make'), classmethod):
# print "no _make"
return False
if not isinstance(cls.__dict__.get('_asdict'), types.FunctionType):
# print "no _asdict"
return False
if not isinstance(cls.__dict__.get('_replace'), types.FunctionType):
# print "no _replace"
return False
return True
class ModuleNamesVisitor(ast.NodeVisitor):
def __init__(self):
self.names = set()
def visit(self, node):
# if we have the module, recurse
if isinstance(node, ast.Module):
self.generic_visit(node)
# we are looking for statements which could define a new name...
elif isinstance(node,
(ast.Assign,
ast.ClassDef,
ast.FunctionDef,
ast.Import,
ast.ImportFrom,
ast.For,
ast.With,
ast.TryExcept,
)):
self.add_names(node)
def add_names(self, obj):
# print "add_names: %r" % obj
# string... add it!
if isinstance(obj, basestring):
self.names.add(obj)
# A name node... add if the context is right
elif isinstance(obj, ast.Name):
if isinstance(obj.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.add_names(obj.id)
# An alias... check for 'foo as bar'
elif isinstance(obj, ast.alias):
if obj.asname:
name = obj.asname
else:
name = obj.name
if name != '*':
self.add_names(name)
# list/tuple.. iterate...
elif isinstance(obj, (list, tuple)):
for item in obj:
self.add_names(item)
elif isinstance(obj, (ast.Tuple, ast.List)):
self.add_names(obj.elts)
# Statements (or subparts)...
elif isinstance(obj, ast.Assign):
self.add_names(obj.targets)
elif isinstance(obj, ast.ClassDef):
self.add_names(obj.name)
elif isinstance(obj, ast.FunctionDef):
self.add_names(obj.name)
elif isinstance(obj, ast.Import):
self.add_names(obj.names)
elif isinstance(obj, ast.ImportFrom):
self.add_names(obj.names)
elif isinstance(obj, ast.For):
self.add_names(obj.target)
elif isinstance(obj, ast.With):
self.add_names(obj.optional_vars)
elif isinstance(obj, ast.TryExcept):
self.add_names(obj.handlers)
elif isinstance(obj, ast.ExceptHandler):
self.add_names(obj.name)
def get_static_module_names(module):
'''Given a module object, tries to do static code analysis to find the names
that will be defined at module level.
'''
path = module.__file__
if path.endswith(('.pyc', '.pyo')):
path = path[:-1]
with open(path, 'r') as f:
text = f.read()
if not text.endswith('\n'):
# for some reason, the parser requires the text end with a newline...
text += '\n'
moduleAst = ast.parse(text, path)
visitor = ModuleNamesVisitor()
visitor.visit(moduleAst)
return visitor.names
def have_id_name(id_to_data, id_obj, name):
"return if the id_object has the passed name"
data = id_to_data.get(id_obj, None)
if data is None:
return False
return name in data[NAMES]
def get_importall_modules(id_to_data, other_module_names):
importall_modules = []
for other_mod, other_id_names in other_module_names.iteritems():
other_all = getattr(other_mod, '__all__', None)
visible_other = 0
in_this = []
for id_obj, other_names in other_id_names.iteritems():
for other_name in other_names:
if not visiblename(other_name, other_all):
continue
visible_other += 1
if have_id_name(id_to_data, id_obj, other_name):
in_this.append((id_obj, other_name))
# rough heuristic - if 90% of the objects can be found in this
# module, we assume an import all was done... note that we're not
# even checking if they're present in this module with the same
# name... it's a rough heuristic anyway...
# chose .85 just because core.language gets .87 in pymel.core
if float(len(in_this)) / visible_other > .85:
importall_modules.append(other_mod)
# go through and REMOVE all the in_this entries from
# id_to_data...
for id_obj, other_name in in_this:
data = id_to_data[id_obj]
data[NAMES].remove(other_name)
if not data[NAMES]:
del id_to_data[id_obj]
return importall_modules
class NoUnicodeTextRepr(TextRepr):
'''PyDev barfs when a unicode literal (ie, u'something') is in a pypredef
file; use this repr to make sure they don't show up.
'''
def __init__(self):
self.maxlevel = 6
self.maxtuple = 100000
self.maxlist = 100000
self.maxarray = 100000
self.maxdict = 100000
self.maxset = 100000
self.maxfrozenset = 100000
self.maxdeque = 100000
self.maxstring = 100000
self.maxlong = 100000
self.maxother = 100000
def repr_unicode(self, uStr, level):
return self.repr_string(str(uStr), level)
def repr1(self, x, level):
# believe it or not there are cases where split(s) fails and s.split()
# succeeds. specifically, I'm seeing this error with a PySide object:
# SystemError: Objects/longobject.c:244: bad argument to internal
# function so this is a slight edit of TextRepr.repr1
if hasattr(type(x), '__name__'):
methodname = 'repr_' + join(type(x).__name__.split(), '_')
if hasattr(self, methodname):
return getattr(self, methodname)(x, level)
return cram(stripid(repr(x)), self.maxother)
class StubDoc(Doc):
"""Formatter class for text documentation."""
# ------------------------------------------- text formatting utilities
_repr_instance = NoUnicodeTextRepr()
# We don't care if it's compact, we just want it to parse right...
repr = _repr_instance.repr
ALLOWABLE_DOUBLE_UNDER_ATTRS = (
'__version__', '__author__', '__date__', '__credits__')
# Mapping of (module, objectsToNeverImportFromIt)
OBJECT_IMPORT_EXCLUDES = {
'ctypes': set(['WinError']),
}
SIMPLE_TYPES = (basestring, bytes, bool, int, long, float, complex)
PASS = 'pass'
UNKNOWN_SIGNATURE = '(*args, **kwargs)'
def __init__(self, import_exclusions=None, import_substitutions=None,
import_filter=None, debugmodules=None, skipdocs=False,
type_data=None, imports_precede_classes=True):
self.missing_modules = set([])
self.module_map = {}
# Mapping of (module, dontImportThese)
self.module_excludes = import_exclusions or {}
self.import_substitutions = import_substitutions or {}
self.import_filter = import_filter
self.debugmodules = debugmodules or ()
self.skipdocs = skipdocs
self.id_map = {}
self.static_module_names = {}
self.safe_constructor_classes = set()
self.type_data = type_data
# a hack to avoid cyclical imports that doesn't always work
self.imports_precede_classes = imports_precede_classes
if hasattr(Doc, '__init__'):
Doc.__init__(self)
# def bold(self, text):
# """Format a string in bold by overstriking."""
# return join(map(lambda ch: ch + '\b' + ch, text), '')
def indent(self, text, prefix=' '):
"""Indent text by prepending a given prefix to each line."""
if not text:
return ''
lines = split(text, '\n')
lines = map(lambda line, prefix=prefix: prefix + line, lines)
if lines:
lines[-1] = rstrip(lines[-1])
return join(lines, '\n')
def docstring(self, contents):
"""Format a section with a given heading."""
quotes = "'''" if '"""' in contents else '"""'
return quotes + '\n' + contents + '\n' + quotes + '\n\n'
# ---------------------------------------------- type-specific routines
def formattree(self, tree, modname, parent=None, prefix=''):
"""Render in text a class tree as returned by inspect.getclasstree()."""
result = ''
for entry in tree:
if type(entry) is type(()):
c, bases = entry
result = result + prefix + self.classname(c, modname)
if bases and bases != (parent,):
parents = map(lambda c, m=modname: self.classname(c, m), bases)
result = result + '(%s)' % join(parents, ', ')
result = result + '\n'
elif type(entry) is type([]):
result = result + self.formattree(
entry, modname, c, prefix + ' ')
return result
def docmodule_add_parent_classes(self, this_module, id_to_data, class_parents, all_names):
def is_module_added(parent_mod):
found_parent_mod = False
if parent_mod:
if id(parent_mod) in id_to_data:
return True
else:
mod_name = parent_mod.__name__
mod_name_split = mod_name.split('.')
while mod_name_split:
mod_name_split.pop()
mod_name = '.'.join(mod_name_split)
parent_mod = sys.modules.get(mod_name, None)
if parent_mod is not None and id(
parent_mod) in id_to_data:
return True
return False
def handle_named_tuple(cls):
if is_named_tuple(cls):
self.docmodule_add_obj(collections.namedtuple, None, id_to_data,
all_names, source_module=collections)
# note that even though we may be adding a new object to the
# module namespace, we don't have to worry about incrementing
# new_to_this_module, as that's only used to signal whether
# we need to continue looking for new parent classes, etc -
# namedtuple is essentially a builtin that we don't need
# to inspect further
return True
return False
# deal with the classes - for classes in this module, we need to
# find their base classes, and make sure they are also defined, or
# imported
untraversed_classes = list(obj for (obj, objtype, source_module, names)
in id_to_data.itervalues()
if objtype == 'class'
and source_module == this_module
and id(obj) not in class_parents)
new_to_this_module = 0
while untraversed_classes:
child_class = untraversed_classes.pop()
if handle_named_tuple(child_class):
continue
try:
parents = [x for x in child_class.__bases__]
except Exception:
print "problem iterating %s.__bases__" % child_class
parents = (object,)
class_parents[id(child_class)] = parents
for parent_class in parents:
# note that even if the parent class is a named tuple,
# we will still need to process it to add it to the module
handle_named_tuple(parent_class)
id_parent = id(parent_class)
parent_mod = inspect.getmodule(parent_class)
if id_parent not in id_to_data:
if parent_class in builtins:
continue
# We've found a class that's not in this namespace...
# ...but perhaps it's parent module is?
if parent_mod and parent_mod is not this_module \
and is_module_added(parent_mod):
# the parent module was there... skip this parent
# class..
continue
# we've found a new class... add it...
new_to_this_module += 1
self.docmodule_add_obj(parent_class, this_module,
id_to_data, all_names)
source_module = id_to_data[id_parent][SOURCEMOD]
if source_module == this_module:
untraversed_classes.append(parent_class)
else:
# make sure that the class's module exists in the
# current namespace
if parent_mod is not None and not \
is_module_added(parent_class):
# perhaps this logic should be handled in docmodule_add_obj.
# we privatize this because we're adding an object which
# did not exist in the original namespace (not in id_to_data)
# so we don't want to cause any conflicts
self.docmodule_add_obj(
parent_mod, this_module, id_to_data, all_names,
name='_' + parent_mod.__name__.split('.')[-1])
return new_to_this_module
def docmodule_add_obj(self, obj, this_module, id_to_data, all_names,
name=None, source_module=None):
id_obj = id(obj)
if id_obj in id_to_data:
# the object was already known - check that the source_module
# is consistent, and add the name if needed
objtype, old_source_module, names = id_to_data[id_obj][OBJTYPE:]
if source_module is None:
# use the old source module..
source_module = old_source_module
# if the source modules are different, but the 'new' module
# is this module, we're okay - we couldn't find the object
# in the desired source_module, so we're just moving it
# into this one...
elif (source_module != old_source_module
and source_module != this_module):
# ...otherwise, something weird is going on...
raise RuntimeError(
"got conflicting source modules for %s" % obj)
# If we don't know the name, and the object already exists in
# the module, then we don't need to do anything... we can just
# use one of the names already assigned to the object...
if name is not None:
# ...otherwise, we need to add the name to list of
# aliases for the object in this module...
if name not in names:
# if __name__ matches name, put the name at the
# front of the list of names, to make it the
# 'default' name...
if getattr(obj, '__name__', None) == name:
names.insert(0, name)
else:
names.append(name)
else:
# the object wasn't known... generate it's info...
if name is None:
# we didn't know the name - generate a unique one, hopefully
# based off the object's name...
name = get_unique_name(getattr(obj, '__name__', None),
all_names=all_names)
if source_module is None:
source_module = get_source_module(obj, this_module)
# now find the objtype...
if inspect.ismodule(obj):
objtype = 'module'
elif inspect.isclass(obj):
objtype = 'class'
elif inspect.isroutine(obj):
objtype = 'func'
else:
objtype = 'data'
names = [name]
id_to_data[id_obj] = (obj, objtype, source_module, names)
def docmodule_get_missing_modules(self, this_module):
return [self.import_mod_text(this_module, mod, '')
for mod in self.missing_modules]
def docmodule(self, this_module, name=None, mod=None, stubmodules=None):
"""Produce text documentation for a given module object."""
this_name = this_module.__name__ # ignore the passed-in name
desc = splitdoc(getdoc(this_module))[1]
self.contents = []
self.module_map = {}
self.id_map = {}
self.missing_modules = set([])
self.safe_constructor_classes = set()
all = getattr(this_module, '__all__', None)
if stubmodules is None:
self.stubmodules = set([this_name])
else:
self.stubmodules = set(stubmodules)
if desc:
self.contents.extend(self.docstring(desc).split('\n'))
# set of all names in this module
all_names = set()
# these are all dicts that key off the object id...
# we index by obj-id, instead of obj, because not all objects are
# hashable, and we really only care about 'is' comparisons, not
# equality comparisons...
# this is a dict that maps from object id to a tuple
# (obj, objtype, source_module, names)
# where obj is the object itself, objtype is one of the strings
# module/class/func/data, and names is a list of the names/aliases under
# which the object can be found in this module.
id_to_data = {}
# add all the objects that we have names for / should be in this
# module
for name, obj in inspect.getmembers(this_module):
if (name.startswith('__') and name.endswith('__')
and name not in self.ALLOWABLE_DOUBLE_UNDER_ATTRS):
continue
self.docmodule_add_obj(obj, this_module, id_to_data, all_names,
name=name)
# We now need to do two things:
# 1) find the parent classes for any classes we will define in this
# module, and make sure that they are accessible under some name
# from within this module
# 2) for all objects we will be importing from other modules, make
# sure we can actually find them under some name in that module;
# if not, change their source_module to THIS module (ie, so we
# define a dummy placeholder for it in this module)
# Since both of these can end up adding new objects to the list of
# objects defined in this module (ie, whose
# source_module == this_module), which can then cause the need to check
# for updates on the other, we run both in a loop until neither task
# finds any new things added to this module's namespace
# maps from the id of a class to it's parent classes, for classes
# which we will define in this module...
class_parents = {}
# maps from an id_obj to its ('default') name in the source module
import_other_name = {}
# maps from module to a dict, mapping from id to names within that
# module
other_module_names = {}
def find_import_data():
unknown_import_objs = list(
(obj, source_module) for (obj, objtype, source_module, names)
in id_to_data.itervalues() if
objtype != 'module' and source_module != this_module
and id(obj) not in import_other_name)
new_to_this_module = 0
for obj, source_module in unknown_import_objs:
id_obj = id(obj)
other_id_names = other_module_names.get(source_module, None)
if other_id_names is None:
other_id_names = {}
for other_name, other_obj in inspect.getmembers(source_module):
id_other = id(other_obj)
other_id_names.setdefault(id_other, []).append(other_name)
other_module_names[source_module] = other_id_names
other_names = other_id_names.get(id_obj, None)
if not other_names:
# we couldn't find obj in the desired module - we'll
# have to move it to this_module...
new_to_this_module += 1
# calling docmodule_add_obj with the same obj but module as
# this_module will update it...
self.docmodule_add_obj(obj, this_module, id_to_data,
all_names, source_module=this_module)
else:
# check to see if we've already found the object
# in the module - if so, only update the name if it's the
# __name__ of the object
name = getattr(obj, '__name__', None)
if name is None or name not in other_names:
name = other_names[0]
import_other_name[id_obj] = name
return new_to_this_module
new_to_this_module = 1
while new_to_this_module:
new_to_this_module = self.docmodule_add_parent_classes(
this_module, id_to_data, class_parents, all_names)
new_to_this_module += find_import_data()
# check the other modules for possible "from mod import *" action...
importall_modules = get_importall_modules(id_to_data, other_module_names)
# We finally have all the objects that will be added to this module
# (with their names in this module), all the parent clases for classes
# defined here, and all the import names for objects being imported...
# Now, sort them all into lists by type for objects defined in in
# this module, and a list of imported for things in other modules...
modules = []
classes = []
funcs = []
data = []
imported = []
bins = {
'module': modules,
'class': classes,
'func': funcs,
'data': data
}
for id_obj, (obj, objtype, source_module, names) in id_to_data.iteritems():
if source_module == this_module or objtype == 'module':
bins[objtype].append((obj, names))
else:
imported.append((obj, names, source_module))
# Before adding things, prepopulate our module_map and id_map
# these are modules which may or may not be used. if we add an import
# line it should be as close to possible to where it is used to avoid
# circular imports
self.maybe_modules = {}
for obj, names in modules:
self.add_to_module_map(obj.__name__, names[0])
for mod in importall_modules:
self.add_to_module_map(mod.__name__, '')
# eventually, might want to replace module_map and id_map
# with id_to_data...
for id_obj, (obj, objtype, source_module, names) in id_to_data.iteritems():
if objtype == 'module':
continue
self.id_map[id_obj] = names[0]
# Finally, go through and start writing stuff out! Go though by type:
#
# 1) module imports
# 2) from MODULE import *
# 3) from MODULE import OBJ
# 4) class definitions
# 5) func defs
# 6) data
if modules: # module imports
for obj, names in modules:
for import_name in names:
realname = getattr(obj, '__name__', None)
if not realname:
print "Warning - could not get a name for module %s" % obj
continue
if realname == this_name:
continue
import_text = self.import_mod_text(this_module, realname,
import_name)
if import_text:
self.maybe_modules[import_name] = import_text
if self.import_filter:
modules, imported, importall_modules = self.import_filter(
this_name, modules, imported, importall_modules)
if importall_modules: # from MODULE import *
for mod in importall_modules:
import_text = self.import_mod_text(this_module, mod.__name__, '*')
if import_text:
self.contents.append(import_text)
self.contents.extend(['', ''])
if imported: # from MODULE import OBJ
for obj, names, source_module in imported:
for name in names:
import_text = self.import_obj_text(source_module.__name__,
import_other_name[id(obj)],
name)
if import_text:
self.contents.append(import_text)
self.contents.extend(['', ''])
# typing module for type-checking in e.g. PyCharm
self.contents.append('if False:\n from typing import Dict, List, Tuple, Union, Optional\n')
if classes:
# sort in order of resolution
def nonconflicting(classlist):
for cls in classlist:
ancestors = set(inspect.getmro(cls)[1:])
if not ancestors.intersection(classlist):
yield cls
sorted = []
unsorted = set([x[0] for x in classes])
while unsorted:
for cls in nonconflicting(unsorted):
sorted.append(cls)
unsorted.difference_update(sorted)
contents = []
classes = dict(classes)
for cls in sorted:
names = classes[cls]
name = names[0]
contents.append(self.document(cls, name, this_name))
for alias in names[1:]:
contents.append('%s = %s' % (alias, name))
# check if it has a default constructor... if so, add to the
# list of classes that it is safe to create...
if has_default_constructor(cls):
self.safe_constructor_classes.add(id(cls))
classres = join(contents, '\n').split('\n')
for i, line in enumerate(classres):
if u'\xa0' in line:
print "bad char"
for j in range(max(i-10, 0), min(i+10, len(classres))):
if j == i:
print '-'*80
print classres[j]
if j == i:
print '-'*80
classres[i] = ''.join(line.split(u'\xa0'))
self.contents.extend(classres)
self.contents.extend(['', ''])
if funcs:
contents = []
for obj, names in funcs:
name = names[0]
contents.append(self.document(obj, name, this_name))
for alias in names[1:]:
contents.append('%s = %s' % (alias, name))
self.contents.extend(contents)
self.contents.extend(['', ''])
if data:
contents = []
for obj, names in data:
name = names[0]
contents.append(self.docother(obj, name, this_name, maxlen=70))
for alias in names[1:]:
contents.append('%s = %s' % (alias, name))
self.contents.extend(contents)
self.contents.extend(['', ''])
# if hasattr(this_module, '__version__'):
# version = str(this_module.__version__)
# if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
# version = strip(version[11:-1])
# result = result + self.section('VERSION', version) + '\n\n'
# if hasattr(this_module, '__date__'):
# result = result + self.section('DATE', str(this_module.__date__)) + '\n\n'
# if hasattr(this_module, '__author__'):
# result = result + self.section('AUTHOR', str(this_module.__author__)) + '\n\n'
# if hasattr(this_module, '__credits__'):
# result = result + self.section('CREDITS', str(this_module.__credits__)) + '\n\n'
missing = self.docmodule_get_missing_modules(this_module)
if missing:
contents = []
for import_text in missing:
if import_text:
contents.append(import_text)
self.contents = contents + ['', ''] + self.contents
result = join(self.contents, '\n')
self.safe_constructor_classes = set()
return result
def add_to_module_map(self, realname, newname):
oldname = self.module_map.get(realname, None)
if oldname is None:
self.module_map[realname] = newname
return
else:
# if either old or new is a 'from realname import *', that's the
# best possible outcome...
if not oldname or not newname:
self.module_map[realname] = ''
return
# otherwise, check to see if one of the names matches the last
# part of realname...
final_name = realname.split('.')[-1]
if final_name in (oldname, newname):
self.module_map[realname] = final_name
return
# otherwise, just take whatever one has the shorter number of
# parts, with tie going to the old_val...
oldnum = len(oldname.split('.'))
newnum = len(newname.split('.'))
if oldnum < newnum:
self.module_map[realname] = oldname
elif oldnum > newnum:
self.module_map[realname] = newname
# tie, do nothing...
return
def _module_has_static_name(self, module, name):
if isinstance(module, basestring):
module = sys.modules[module]
elif not isinstance(module, types.ModuleType):
raise TypeError(module)
if module not in self.static_module_names:
self.static_module_names[module] = get_static_module_names(module)
return name in self.static_module_names[module]
def classname(self, klass, modname, realmodule=None, consume_import=False):
"""Get a class name and qualify it with a module name if necessary."""
if id(klass) in self.id_map:
result = self.id_map[id(klass)]
if consume_import:
return result, None