Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 35.2k
Expand file tree
/
Copy pathinspect.py
More file actions
Latest commit
3510 lines (2999 loc) · 128 KB
/
Copy pathinspect.py
File metadata and controls
3510 lines (2999 loc) · 128 KB
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
"""Get useful information from live Python objects.
This module encapsulates the interface provided by the internal special
attributes (co_*, tb_*, etc.) in a friendlier fashion.
It also provides some help for examining source code and class layout.
Here are some of the useful functions provided by this module:
ismodule(), isclass(), ismethod(), ispackage(), isfunction(),
isgeneratorfunction(), isgenerator(), istraceback(), isframe(),
iscode(), isbuiltin(), isroutine() - check object types
getmembers() - get members of an object that satisfy a given condition
getfile(), getsourcefile(), getsource() - find an object's source code
getdoc(), getcomments() - get documentation on an object
getmodule() - determine the module that an object came from
getclasstree() - arrange classes so as to represent their hierarchy
getargvalues(), getcallargs() - get info about function arguments
getfullargspec() - same, with support for Python 3 features
formatargvalues() - format an argument spec
getouterframes(), getinnerframes() - get info about frames
currentframe() - get the current stack frame
stack(), trace() - get info about frames on the stack or in a traceback
signature() - get a Signature object for the callable
"""
# This module is in the public domain. No warranties.
__author__= ('Ka-Ping Yee <ping@lfw.org>',
'Yury Selivanov <yselivanov@sprymix.com>')
__all__= [
"AGEN_CLOSED",
"AGEN_CREATED",
"AGEN_RUNNING",
"AGEN_SUSPENDED",
"ArgInfo",
"Arguments",
"Attribute",
"BlockFinder",
"BoundArguments",
"BufferFlags",
"CORO_CLOSED",
"CORO_CREATED",
"CORO_RUNNING",
"CORO_SUSPENDED",
"CO_ASYNC_GENERATOR",
"CO_COROUTINE",
"CO_GENERATOR",
"CO_ITERABLE_COROUTINE",
"CO_NESTED",
"CO_NEWLOCALS",
"CO_NOFREE",
"CO_OPTIMIZED",
"CO_VARARGS",
"CO_VARKEYWORDS",
"CO_HAS_DOCSTRING",
"CO_METHOD",
"ClassFoundException",
"ClosureVars",
"EndOfBlock",
"FrameInfo",
"FullArgSpec",
"GEN_CLOSED",
"GEN_CREATED",
"GEN_RUNNING",
"GEN_SUSPENDED",
"Parameter",
"Signature",
"TPFLAGS_IS_ABSTRACT",
"Traceback",
"classify_class_attrs",
"cleandoc",
"currentframe",
"findsource",
"formatannotation",
"formatannotationrelativeto",
"formatargvalues",
"get_annotations",
"getabsfile",
"getargs",
"getargvalues",
"getasyncgenlocals",
"getasyncgenstate",
"getattr_static",
"getblock",
"getcallargs",
"getclasstree",
"getclosurevars",
"getcomments",
"getcoroutinelocals",
"getcoroutinestate",
"getdoc",
"getfile",
"getframeinfo",
"getfullargspec",
"getgeneratorlocals",
"getgeneratorstate",
"getinnerframes",
"getlineno",
"getmembers",
"getmembers_static",
"getmodule",
"getmodulename",
"getmro",
"getouterframes",
"getsource",
"getsourcefile",
"getsourcelines",
"indentsize",
"isabstract",
"isasyncgen",
"isasyncgenfunction",
"isawaitable",
"isbuiltin",
"isclass",
"iscode",
"iscoroutine",
"iscoroutinefunction",
"isdatadescriptor",
"isframe",
"isfunction",
"isgenerator",
"isgeneratorfunction",
"isgetsetdescriptor",
"ismemberdescriptor",
"ismethod",
"ismethoddescriptor",
"ismethodwrapper",
"ismodule",
"ispackage",
"isroutine",
"istraceback",
"markcoroutinefunction",
"signature",
"stack",
"trace",
"unwrap",
"walktree",
]
importabc
fromannotationlibimportFormat, ForwardRef
fromannotationlibimportget_annotations# re-exported
importast
importdis
importcollections.abc
importenum
importimportlib.machinery
importitertools
importlinecache
importos
lazyimportre
importsys
lazyimporttokenize
importtoken
importtypes
importfunctools
importbuiltins
fromkeywordimportiskeyword
fromoperatorimportattrgetter
fromcollectionsimportnamedtuple, OrderedDict
from_weakrefimportrefasmake_weakref
# Create constants for the compiler flags in Include/cpython/code.h
# We try to get them from dis to avoid duplication
mod_dict=globals()
fork, vindis.COMPILER_FLAG_NAMES.items():
mod_dict["CO_"+v] =k
delk, v, mod_dict
# See Include/object.h
TPFLAGS_IS_ABSTRACT=1<<20
# ----------------------------------------------------------- type-checking
defismodule(object):
"""Return true if the object is a module."""
returnisinstance(object, types.ModuleType)
defisclass(object):
"""Return true if the object is a class."""
returnisinstance(object, type)
defismethod(object):
"""Return true if the object is an instance method."""
returnisinstance(object, types.MethodType)
defispackage(object):
"""Return true if the object is a package."""
returnismodule(object) andhasattr(object, "__path__")
defismethoddescriptor(object):
"""Return true if the object is a method descriptor.
But not if ismethod(), isclass() or isfunction() is true.
An object passing this test (for example, int.__add__) has a __get__
attribute, but not a __set__ attribute or a __delete__ attribute.
Beyond that, the set of attributes varies; __name__ is usually
sensible, and __doc__ often is.
Methods implemented via descriptors that also pass one of the other
tests (ismethod(), isclass(), isfunction()) make this function return
false, simply because those other tests promise more -- you can, for
example, count on having the __func__ attribute when an object passes
ismethod()."""
ifisclass(object) orismethod(object) orisfunction(object):
# mutual exclusion
returnFalse
tp=type(object)
return (hasattr(tp, "__get__")
andnothasattr(tp, "__set__")
andnothasattr(tp, "__delete__"))
defisdatadescriptor(object):
"""Return true if the object is a data descriptor.
But not if ismethod(), isclass() or isfunction() is true.
Data descriptors have a __set__ or a __delete__ attribute. Examples are
properties, getsets, and members. For the latter two (defined only in C
extension modules) more specific tests are available as well:
isgetsetdescriptor() and ismemberdescriptor(), respectively.
Typically, data descriptors will also have __name__ and __doc__ attributes
(properties, getsets, and members have both of these attributes), but this
is not guaranteed."""
ifisclass(object) orismethod(object) orisfunction(object):
# mutual exclusion
returnFalse
tp=type(object)
returnhasattr(tp, "__set__") orhasattr(tp, "__delete__")
ifhasattr(types, 'MemberDescriptorType'):
# CPython and equivalent
defismemberdescriptor(object):
"""Return true if the object is a member descriptor.
Member descriptors are specialized descriptors defined in extension
modules."""
returnisinstance(object, types.MemberDescriptorType)
else:
# Other implementations
defismemberdescriptor(object):
"""Return true if the object is a member descriptor.
Member descriptors are specialized descriptors defined in extension
modules."""
returnFalse
ifhasattr(types, 'GetSetDescriptorType'):
# CPython and equivalent
defisgetsetdescriptor(object):
"""Return true if the object is a getset descriptor.
getset descriptors are specialized descriptors defined in extension
modules."""
returnisinstance(object, types.GetSetDescriptorType)
else:
# Other implementations
defisgetsetdescriptor(object):
"""Return true if the object is a getset descriptor.
getset descriptors are specialized descriptors defined in extension
modules."""
returnFalse
defisfunction(object):
"""Return true if the object is a user-defined function.
Function objects provide these attributes:
__doc__ documentation string
__name__ name with which this function was defined
__qualname__ qualified name of this function
__module__ name of the module the function was defined in or None
__code__ code object containing compiled function bytecode
__defaults__ tuple of any default values for arguments
__globals__ global namespace in which this function was defined
__annotations__ dict of parameter annotations
__kwdefaults__ dict of keyword only parameters with defaults
__dict__ namespace which is supporting arbitrary function attributes
__closure__ a tuple of cells or None
__type_params__ tuple of type parameters"""
returnisinstance(object, types.FunctionType)
def_has_code_flag(f, flag):
"""Return true if ``f`` is a function (or a method or functools.partial
wrapper wrapping a function or a functools.partialmethod wrapping a
function) whose code object has the given ``flag``
set in its flags."""
f=functools._unwrap_partialmethod(f)
whileismethod(f):
f=f.__func__
f=functools._unwrap_partial(f)
ifnot (isfunction(f) or_signature_is_functionlike(f)):
returnFalse
returnbool(f.__code__.co_flags&flag)
defisgeneratorfunction(obj):
"""Return true if the object is a user-defined generator function.
Generator function objects provide the same attributes as functions.
See help(isfunction) for a list of attributes."""
return_has_code_flag(obj, CO_GENERATOR)
# A marker for markcoroutinefunction and iscoroutinefunction.
_is_coroutine_mark=object()
def_has_coroutine_mark(f):
whileismethod(f):
f=f.__func__
f=functools._unwrap_partial(f)
returngetattr(f, "_is_coroutine_marker", None) is_is_coroutine_mark
defmarkcoroutinefunction(func):
"""
Decorator to ensure callable is recognised as a coroutine function.
"""
ifhasattr(func, '__func__'):
func=func.__func__
func._is_coroutine_marker=_is_coroutine_mark
returnfunc
defiscoroutinefunction(obj):
"""Return true if the object is a coroutine function.
Coroutine functions are normally defined with "async def" syntax, but may
be marked via markcoroutinefunction.
"""
return_has_code_flag(obj, CO_COROUTINE) or_has_coroutine_mark(obj)
defisasyncgenfunction(obj):
"""Return true if the object is an asynchronous generator function.
Asynchronous generator functions are defined with "async def"
syntax and have "yield" expressions in their body.
"""
return_has_code_flag(obj, CO_ASYNC_GENERATOR)
defisasyncgen(object):
"""Return true if the object is an asynchronous generator."""
returnisinstance(object, types.AsyncGeneratorType)
defisgenerator(object):
"""Return true if the object is a generator.
Generator objects provide these attributes:
gi_code code object
gi_frame frame object or possibly None once the generator has
been exhausted
gi_running set to 1 when generator is executing, 0 otherwise
gi_suspended set to 1 when the generator is suspended at a yield point, 0 otherwise
gi_yieldfrom object being iterated by yield from or None
__iter__() defined to support iteration over container
close() raises a new GeneratorExit exception inside the
generator to terminate the iteration
send() resumes the generator and "sends" a value that becomes
the result of the current yield-expression
throw() used to raise an exception inside the generator"""
returnisinstance(object, types.GeneratorType)
defiscoroutine(object):
"""Return true if the object is a coroutine."""
returnisinstance(object, types.CoroutineType)
defisawaitable(object):
"""Return true if object can be passed to an ``await`` expression."""
return (isinstance(object, types.CoroutineType) or
isinstance(object, types.GeneratorType) and
bool(object.gi_code.co_flags&CO_ITERABLE_COROUTINE) or
isinstance(object, collections.abc.Awaitable))
defistraceback(object):
"""Return true if the object is a traceback.
Traceback objects provide these attributes:
tb_frame frame object at this level
tb_lasti index of last attempted instruction in bytecode
tb_lineno current line number in Python source code
tb_next next inner traceback object (called by this level)"""
returnisinstance(object, types.TracebackType)
defisframe(object):
"""Return true if the object is a frame object.
Frame objects provide these attributes:
f_back next outer frame object (this frame's caller)
f_builtins built-in namespace seen by this frame
f_code code object being executed in this frame
f_globals global namespace seen by this frame
f_lasti index of last attempted instruction in bytecode
f_lineno current line number in Python source code
f_locals local namespace seen by this frame
f_trace tracing function for this frame, or None
f_trace_lines is a tracing event triggered for each source line?
f_trace_opcodes are per-opcode events being requested?
clear() used to clear all references to local variables"""
returnisinstance(object, types.FrameType)
defiscode(object):
"""Return true if the object is a code object.
Code objects provide these attributes:
co_argcount number of arguments (not including *, ** args
or keyword only arguments)
co_code string of raw compiled bytecode
co_cellvars tuple of names of cell variables
co_consts tuple of constants used in the bytecode
co_filename name of file in which this code object was created
co_firstlineno number of first line in Python source code
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
| 16=nested | 32=generator | 64=nofree | 128=coroutine
| 256=iterable_coroutine | 512=async_generator
| 0x4000000=has_docstring
co_freevars tuple of names of free variables
co_posonlyargcount number of positional only arguments
co_kwonlyargcount number of keyword only arguments (not including ** arg)
co_name name with which this code object was defined
co_names tuple of names other than arguments and function locals
co_nlocals number of local variables
co_stacksize virtual machine stack space required
co_varnames tuple of names of arguments and local variables
co_qualname fully qualified function name
co_lines() returns an iterator that yields successive bytecode ranges
co_positions() returns an iterator of source code positions for each bytecode instruction
replace() returns a copy of the code object with a new values"""
returnisinstance(object, types.CodeType)
defisbuiltin(object):
"""Return true if the object is a built-in function or method.
Built-in functions and methods provide these attributes:
__doc__ documentation string
__name__ original name of this function or method
__self__ instance to which a method is bound, or None"""
returnisinstance(object, types.BuiltinFunctionType)
defismethodwrapper(object):
"""Return true if the object is a method wrapper."""
returnisinstance(object, types.MethodWrapperType)
defisroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
orisfunction(object)
orismethod(object)
orismethoddescriptor(object)
orismethodwrapper(object)
orisinstance(object, functools._singledispatchmethod_get))
defisabstract(object):
"""Return true if the object is an abstract base class (ABC)."""
ifnotisinstance(object, type):
returnFalse
ifobject.__flags__&TPFLAGS_IS_ABSTRACT:
returnTrue
ifnotissubclass(type(object), abc.ABCMeta):
returnFalse
ifhasattr(object, '__abstractmethods__'):
# It looks like ABCMeta.__new__ has finished running;
# TPFLAGS_IS_ABSTRACT should have been accurate.
returnFalse
# It looks like ABCMeta.__new__ has not finished running yet; we're
# probably in __init_subclass__. We'll look for abstractmethods manually.
forname, valueinobject.__dict__.items():
ifgetattr(value, "__isabstractmethod__", False):
returnTrue
forbaseinobject.__bases__:
fornameingetattr(base, "__abstractmethods__", ()):
value=getattr(object, name, None)
ifgetattr(value, "__isabstractmethod__", False):
returnTrue
returnFalse
def_getmembers(object, predicate, getter):
results= []
processed=set()
names=dir(object)
ifisclass(object):
mro=getmro(object)
# add any DynamicClassAttributes to the list of names if object is a class;
# this may result in duplicate entries if, for example, a virtual
# attribute with the same name as a DynamicClassAttribute exists
try:
forbaseinobject.__bases__:
fork, vinbase.__dict__.items():
ifisinstance(v, types.DynamicClassAttribute):
names.append(k)
exceptAttributeError:
pass
else:
mro= ()
forkeyinnames:
# First try to get the value via getattr. Some descriptors don't
# like calling their __get__ (see bug #1785), so fall back to
# looking in the __dict__.
try:
value=getter(object, key)
# handle the duplicate key
ifkeyinprocessed:
raiseAttributeError
exceptAttributeError:
forbaseinmro:
ifkeyinbase.__dict__:
value=base.__dict__[key]
break
else:
# could be a (currently) missing slot member, or a buggy
# __dir__; discard and move on
continue
ifnotpredicateorpredicate(value):
results.append((key, value))
processed.add(key)
results.sort(key=lambdapair: pair[0])
returnresults
defgetmembers(object, predicate=None):
"""Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate."""
return_getmembers(object, predicate, getattr)
defgetmembers_static(object, predicate=None):
"""Return all members of an object as (name, value) pairs sorted by name
without triggering dynamic lookup via the descriptor protocol,
__getattr__ or __getattribute__. Optionally, only return members that
satisfy a given predicate.
Note: this function may not be able to retrieve all members
that getmembers can fetch (like dynamically created attributes)
and may find members that getmembers can't (like descriptors
that raise AttributeError). It can also return descriptor objects
instead of instance members in some cases.
"""
return_getmembers(object, predicate, getattr_static)
Attribute=namedtuple('Attribute', 'name kind defining_class object')
defclassify_class_attrs(cls):
"""Return list of attribute-descriptor tuples.
For each name in dir(cls), the return list contains a 4-tuple
with these elements:
0. The name (a string).
1. The kind of attribute this is, one of these strings:
'class method' created via classmethod()
'static method' created via staticmethod()
'property' created via property()
'method' any other flavor of method or descriptor
'data' not a method
2. The class which defined this attribute (a class).
3. The object as obtained by calling getattr; if this fails, or if the
resulting object does not live anywhere in the class' mro (including
metaclasses) then the object is looked up in the defining class's
dict (found by walking the mro).
If one of the items in dir(cls) is stored in the metaclass it will now
be discovered and not have None be listed as the class in which it was
defined. Any items whose home class cannot be discovered are skipped.
"""
mro=getmro(cls)
metamro=getmro(type(cls)) # for attributes stored in the metaclass
metamro=tuple(clsforclsinmetamroifclsnotin (type, object))
class_bases= (cls,) +mro
all_bases=class_bases+metamro
names=dir(cls)
# :dd any DynamicClassAttributes to the list of names;
# this may result in duplicate entries if, for example, a virtual
# attribute with the same name as a DynamicClassAttribute exists.
forbaseinmro:
fork, vinbase.__dict__.items():
ifisinstance(v, types.DynamicClassAttribute) andv.fgetisnotNone:
names.append(k)
result= []
processed=set()
fornameinnames:
# Get the object associated with the name, and where it was defined.
# Normal objects will be looked up with both getattr and directly in
# its class' dict (in case getattr fails [bug #1785], and also to look
# for a docstring).
# For DynamicClassAttributes on the second pass we only look in the
# class's dict.
#
# Getting an obj from the __dict__ sometimes reveals more than
# using getattr. Static and class methods are dramatic examples.
homecls=None
get_obj=None
dict_obj=None
ifnamenotinprocessed:
try:
ifname=='__dict__':
raiseException("__dict__ is special, don't want the proxy")
get_obj=getattr(cls, name)
exceptException:
pass
else:
homecls=getattr(get_obj, "__objclass__", homecls)
ifhomeclsnotinclass_bases:
# if the resulting object does not live somewhere in the
# mro, drop it and search the mro manually
homecls=None
last_cls=None
# first look in the classes
forsrch_clsinclass_bases:
srch_obj=getattr(srch_cls, name, None)
ifsrch_objisget_obj:
last_cls=srch_cls
# then check the metaclasses
forsrch_clsinmetamro:
try:
srch_obj=srch_cls.__getattr__(cls, name)
exceptAttributeError:
continue
ifsrch_objisget_obj:
last_cls=srch_cls
iflast_clsisnotNone:
homecls=last_cls
forbaseinall_bases:
ifnameinbase.__dict__:
dict_obj=base.__dict__[name]
ifhomeclsnotinmetamro:
homecls=base
break
ifhomeclsisNone:
# unable to locate the attribute anywhere, most likely due to
# buggy custom __dir__; discard and move on
continue
obj=get_objifget_objisnotNoneelsedict_obj
# Classify the object or its descriptor.
ifisinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):
kind="static method"
obj=dict_obj
elifisinstance(dict_obj, (classmethod, types.ClassMethodDescriptorType)):
kind="class method"
obj=dict_obj
elifisinstance(dict_obj, property):
kind="property"
obj=dict_obj
elifisroutine(obj):
kind="method"
else:
kind="data"
result.append(Attribute(name, kind, homecls, obj))
processed.add(name)
returnresult
# ----------------------------------------------------------- class helpers
defgetmro(cls):
"Return tuple of base classes (including cls) in method resolution order."
returncls.__mro__
# -------------------------------------------------------- function helpers
defunwrap(func, *, stop=None):
"""Get the object wrapped by *func*.
Follows the chain of :attr:`__wrapped__` attributes returning the last
object in the chain.
*stop* is an optional callback accepting an object in the wrapper chain
as its sole argument that allows the unwrapping to be terminated early if
the callback returns a true value. If the callback never returns a true
value, the last object in the chain is returned as usual. For example,
:func:`signature` uses this to stop unwrapping if any object in the
chain has a ``__signature__`` attribute defined.
:exc:`ValueError` is raised if a cycle is encountered.
"""
f=func# remember the original func for error reporting
# Memoise by id to tolerate non-hashable objects, but store objects to
# ensure they aren't destroyed, which would allow their IDs to be reused.
memo= {id(f): f}
recursion_limit=sys.getrecursionlimit()
whilenotisinstance(func, type) andhasattr(func, '__wrapped__'):
ifstopisnotNoneandstop(func):
break
func=func.__wrapped__
id_func=id(func)
if (id_funcinmemo) or (len(memo) >=recursion_limit):
raiseValueError('wrapper loop when unwrapping {!r}'.format(f))
memo[id_func] =func
returnfunc
# -------------------------------------------------- source code extraction
defindentsize(line):
"""Return the indent size, in spaces, at the start of a line of text."""
expline=line.expandtabs()
returnlen(expline) -len(expline.lstrip())
def_findclass(func):
cls=sys.modules.get(func.__module__)
ifclsisNone:
returnNone
fornameinfunc.__qualname__.split('.')[:-1]:
cls=getattr(cls, name)
ifnotisclass(cls):
returnNone
returncls
def_finddoc(obj, *, search_in_class=True):
ifsearch_in_classandisclass(obj):
forbaseinobj.__mro__:
ifbaseisnotobject:
try:
doc=base.__doc__
exceptAttributeError:
continue
ifdocisnotNone:
returndoc
returnNone
ifismethod(obj):
name=obj.__func__.__name__
self=obj.__self__
if (isclass(self) and
getattr(getattr(self, name, None), '__func__') isobj.__func__):
# classmethod
cls=self
else:
cls=self.__class__
elifisfunction(obj):
name=obj.__name__
cls=_findclass(obj)
ifclsisNoneorgetattr(cls, name) isnotobj:
returnNone
elifisbuiltin(obj):
name=obj.__name__
self=obj.__self__
if (isclass(self) and
self.__qualname__+'.'+name==obj.__qualname__):
# classmethod
cls=self
else:
cls=self.__class__
# Should be tested before isdatadescriptor().
elifisinstance(obj, property):
name=obj.__name__
cls=_findclass(obj.fget)
ifclsisNoneorgetattr(cls, name) isnotobj:
returnNone
# Should be tested before ismethoddescriptor()
elifisinstance(obj, functools.cached_property):
name=obj.attrname
cls=_findclass(obj.func)
ifclsisNoneorgetattr(cls, name) isnotobj:
returnNone
elifismethoddescriptor(obj) orisdatadescriptor(obj):
name=obj.__name__
cls=obj.__objclass__
ifgetattr(cls, name) isnotobj:
returnNone
ifismemberdescriptor(obj):
slots=getattr(cls, '__slots__', None)
ifisinstance(slots, dict) andnameinslots:
returnslots[name]
else:
returnNone
forbaseincls.__mro__:
try:
doc=getattr(base, name).__doc__
exceptAttributeError:
continue
ifdocisnotNone:
returndoc
returnNone
def_getowndoc(obj):
"""Get the documentation string for an object if it is not
inherited from its class."""
try:
doc=object.__getattribute__(obj, '__doc__')
ifdocisNone:
returnNone
ifobjisnottype:
typedoc=type(obj).__doc__
ifisinstance(typedoc, str) andtypedoc==doc:
returnNone
returndoc
exceptAttributeError:
returnNone
defgetdoc(object, *, fallback_to_class_doc=True, inherit_class_doc=True,
dedent=True):
"""Get the documentation string for an object.
All tabs are expanded to spaces. To clean up docstrings that are
indented to line up with blocks of code, any whitespace than can be
uniformly removed from the second line onwards is removed, unless
dedent is false."""
iffallback_to_class_doc:
try:
doc=object.__doc__
exceptAttributeError:
returnNone
else:
doc=_getowndoc(object)
ifdocisNone:
try:
doc=_finddoc(object, search_in_class=inherit_class_doc)
except (AttributeError, TypeError):
returnNone
ifnotisinstance(doc, str):
returnNone
returncleandoc(doc, dedent=dedent)
defcleandoc(doc, *, dedent=True):
"""Clean up indentation from docstrings.
Any whitespace that can be uniformly removed from the second line
onwards is removed, unless dedent is false."""
lines=doc.expandtabs().split('\n')
# Find minimum indentation of any non-blank lines after first line.
margin=sys.maxsize
ifdedent:
forlineinlines[1:]:
content=len(line.lstrip(' '))
ifcontent:
indent=len(line) -content
margin=min(margin, indent)
# Remove indentation.
iflines:
lines[0] =lines[0].lstrip(' ')
ifmargin<sys.maxsize:
foriinrange(1, len(lines)):
lines[i] =lines[i][margin:]
# Remove any trailing or leading blank lines.
whilelinesandnotlines[-1]:
lines.pop()
whilelinesandnotlines[0]:
lines.pop(0)
return'\n'.join(lines)
defgetfile(object):
"""Work out which source or compiled file an object was defined in."""
ifismodule(object):
ifgetattr(object, '__file__', None):
returnobject.__file__
raiseTypeError('{!r} is a built-in module'.format(object))
ifisclass(object):
ifhasattr(object, '__module__'):
module=sys.modules.get(object.__module__)
ifgetattr(module, '__file__', None):
returnmodule.__file__
ifobject.__module__=='__main__':
raiseOSError('source code not available')
raiseTypeError('{!r} is a built-in class'.format(object))
ifismethod(object):
object=object.__func__
ifisfunction(object):
object=object.__code__
ifistraceback(object):
object=object.tb_frame
ifisframe(object):
object=object.f_code
ifiscode(object):
returnobject.co_filename
raiseTypeError('module, class, method, function, traceback, frame, or '
'code object was expected, got {}'.format(
type(object).__name__))
defgetmodulename(path):
"""Return the module name for a given file, or None."""
fname=os.path.basename(path)
# Check for paths that look like an actual module file
suffixes= [(-len(suffix), suffix)
forsuffixinimportlib.machinery.all_suffixes()]
suffixes.sort() # try longest suffixes first, in case they overlap
forneglen, suffixinsuffixes:
iffname.endswith(suffix):
returnfname[:neglen]
returnNone
defgetsourcefile(object):
"""Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source.
"""
filename=getfile(object)
all_bytecode_suffixes=importlib.machinery.BYTECODE_SUFFIXES[:]
ifany(filename.endswith(s) forsinall_bytecode_suffixes):
filename= (os.path.splitext(filename)[0] +
importlib.machinery.SOURCE_SUFFIXES[0])
elifany(filename.endswith(s) forsin
importlib.machinery.EXTENSION_SUFFIXES):
returnNone
eliffilename.endswith(".fwork"):
# Apple mobile framework markers are another type of non-source file
returnNone
# return a filename found in the linecache even if it doesn't exist on disk
iffilenameinlinecache.cache:
returnfilename
ifos.path.exists(filename):
returnfilename
# only return a non-existent filename if the module has a PEP 302 loader
module=getmodule(object, filename)
ifgetattr(module, '__loader__', None) isnotNone:
returnfilename
elifgetattr(getattr(module, "__spec__", None), "loader", None) isnotNone:
returnfilename
defgetabsfile(object, _filename=None):
"""Return an absolute path to the source or compiled file for an object.
The idea is for each object to have a unique origin, so this routine
normalizes the result as much as possible."""
if_filenameisNone:
_filename=getsourcefile(object) orgetfile(object)
returnos.path.normcase(os.path.abspath(_filename))
modulesbyfile= {}
_filesbymodname= {}
defgetmodule(object, _filename=None):
"""Return the module an object was defined in, or None if not found."""
ifismodule(object):
returnobject
ifhasattr(object, '__module__'):
returnsys.modules.get(object.__module__)
# Try the filename to modulename cache
if_filenameisnotNoneand_filenameinmodulesbyfile:
returnsys.modules.get(modulesbyfile[_filename])
# Try the cache again with the absolute file name
try:
file=getabsfile(object, _filename)
except (TypeError, FileNotFoundError):
returnNone
iffileinmodulesbyfile:
returnsys.modules.get(modulesbyfile[file])
# Update the filename to module name cache and check yet again
# Copy sys.modules in order to cope with changes while iterating
formodname, moduleinsys.modules.copy().items():
ifismodule(module) andhasattr(module, '__file__'):
f=module.__file__
iff==_filesbymodname.get(modname, None):
# Have already mapped this module, so skip it
continue
_filesbymodname[modname] =f
f=getabsfile(module)
# Always map to the name the module knows itself by
modulesbyfile[f] =modulesbyfile[
os.path.realpath(f)] =module.__name__
iffileinmodulesbyfile:
returnsys.modules.get(modulesbyfile[file])
# Check the main module
main=sys.modules['__main__']
ifnothasattr(object, '__name__'):
returnNone
ifhasattr(main, object.__name__):
mainobject=getattr(main, object.__name__)
ifmainobjectisobject:
returnmain
# Check builtins
builtin=sys.modules['builtins']
ifhasattr(builtin, object.__name__):
builtinobject=getattr(builtin, object.__name__)
ifbuiltinobjectisobject:
returnbuiltin
classClassFoundException(Exception):
pass
deffindsource(object):
"""Return the entire source file and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of all the lines
in the file and the line number indexes a line in that list. An OSError
is raised if the source code cannot be retrieved."""
file=getsourcefile(object)
iffile:
# Invalidate cache if needed.
linecache.checkcache(file)
else:
file=getfile(object)
# Allow filenames in form of "<something>" to pass through.
# `doctest` monkeypatches `linecache` module to enable
# inspection, so let `linecache.getlines` to be called.
if (not (file.startswith('<') andfile.endswith('>'))) orfile.endswith('.fwork'):
raiseOSError('source code not available')