FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[Original HTTPS Page]
cpython/Lib/inspect.py at 3.14 · python/cpython · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
python
/
cpython
Public
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
Star
74.4k
Code
Issues
5k+
Pull requests
2.5k
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpython
/
Lib
/
inspect.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
3418 lines (2911 loc) · 125 KB
Breadcrumbs
cpython
/
Lib
/
inspect.py
Copy path
File metadata and controls
3418 lines (2911 loc) · 125 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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"
,
]
import
abc
from
annotationlib
import
Format
,
ForwardRef
from
annotationlib
import
get_annotations
# re-exported
import
ast
import
dis
import
collections
.
abc
import
enum
import
importlib
.
machinery
import
itertools
import
linecache
import
os
import
re
import
sys
import
tokenize
import
token
import
types
import
functools
import
builtins
from
keyword
import
iskeyword
from
operator
import
attrgetter
from
collections
import
namedtuple
,
OrderedDict
from
weakref
import
ref
as
make_weakref
# Create constants for the compiler flags in Include/code.h
# We try to get them from dis to avoid duplication
mod_dict
=
globals
()
for
k
,
v
in
dis
.
COMPILER_FLAG_NAMES
.
items
():
mod_dict
[
"CO_"
+
v
]
=
k
del
k
,
v
,
mod_dict
# See Include/object.h
TPFLAGS_IS_ABSTRACT
=
1
<<
20
# ----------------------------------------------------------- type-checking
def
ismodule
(
object
):
"""Return true if the object is a module."""
return
isinstance
(
object
,
types
.
ModuleType
)
def
isclass
(
object
):
"""Return true if the object is a class."""
return
isinstance
(
object
,
type
)
def
ismethod
(
object
):
"""Return true if the object is an instance method."""
return
isinstance
(
object
,
types
.
MethodType
)
def
ispackage
(
object
):
"""Return true if the object is a package."""
return
ismodule
(
object
)
and
hasattr
(
object
,
"__path__"
)
def
ismethoddescriptor
(
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()."""
if
isclass
(
object
)
or
ismethod
(
object
)
or
isfunction
(
object
):
# mutual exclusion
return
False
tp
=
type
(
object
)
return
(
hasattr
(
tp
,
"__get__"
)
and
not
hasattr
(
tp
,
"__set__"
)
and
not
hasattr
(
tp
,
"__delete__"
))
def
isdatadescriptor
(
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."""
if
isclass
(
object
)
or
ismethod
(
object
)
or
isfunction
(
object
):
# mutual exclusion
return
False
tp
=
type
(
object
)
return
hasattr
(
tp
,
"__set__"
)
or
hasattr
(
tp
,
"__delete__"
)
if
hasattr
(
types
,
'MemberDescriptorType'
):
# CPython and equivalent
def
ismemberdescriptor
(
object
):
"""Return true if the object is a member descriptor.
Member descriptors are specialized descriptors defined in extension
modules."""
return
isinstance
(
object
,
types
.
MemberDescriptorType
)
else
:
# Other implementations
def
ismemberdescriptor
(
object
):
"""Return true if the object is a member descriptor.
Member descriptors are specialized descriptors defined in extension
modules."""
return
False
if
hasattr
(
types
,
'GetSetDescriptorType'
):
# CPython and equivalent
def
isgetsetdescriptor
(
object
):
"""Return true if the object is a getset descriptor.
getset descriptors are specialized descriptors defined in extension
modules."""
return
isinstance
(
object
,
types
.
GetSetDescriptorType
)
else
:
# Other implementations
def
isgetsetdescriptor
(
object
):
"""Return true if the object is a getset descriptor.
getset descriptors are specialized descriptors defined in extension
modules."""
return
False
def
isfunction
(
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"""
return
isinstance
(
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
)
while
ismethod
(
f
):
f
=
f
.
__func__
f
=
functools
.
_unwrap_partial
(
f
)
if
not
(
isfunction
(
f
)
or
_signature_is_functionlike
(
f
)):
return
False
return
bool
(
f
.
__code__
.
co_flags
&
flag
)
def
isgeneratorfunction
(
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
):
while
ismethod
(
f
):
f
=
f
.
__func__
f
=
functools
.
_unwrap_partial
(
f
)
return
getattr
(
f
,
"_is_coroutine_marker"
,
None
)
is
_is_coroutine_mark
def
markcoroutinefunction
(
func
):
"""
Decorator to ensure callable is recognised as a coroutine function.
"""
if
hasattr
(
func
,
'__func__'
):
func
=
func
.
__func__
func
.
_is_coroutine_marker
=
_is_coroutine_mark
return
func
def
iscoroutinefunction
(
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
)
def
isasyncgenfunction
(
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
)
def
isasyncgen
(
object
):
"""Return true if the object is an asynchronous generator."""
return
isinstance
(
object
,
types
.
AsyncGeneratorType
)
def
isgenerator
(
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"""
return
isinstance
(
object
,
types
.
GeneratorType
)
def
iscoroutine
(
object
):
"""Return true if the object is a coroutine."""
return
isinstance
(
object
,
types
.
CoroutineType
)
def
isawaitable
(
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
))
def
istraceback
(
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)"""
return
isinstance
(
object
,
types
.
TracebackType
)
def
isframe
(
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"""
return
isinstance
(
object
,
types
.
FrameType
)
def
iscode
(
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_lnotab encoded mapping of line numbers to bytecode indices
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"""
return
isinstance
(
object
,
types
.
CodeType
)
def
isbuiltin
(
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"""
return
isinstance
(
object
,
types
.
BuiltinFunctionType
)
def
ismethodwrapper
(
object
):
"""Return true if the object is a method wrapper."""
return
isinstance
(
object
,
types
.
MethodWrapperType
)
def
isroutine
(
object
):
"""Return true if the object is any kind of function or method."""
return
(
isbuiltin
(
object
)
or
isfunction
(
object
)
or
ismethod
(
object
)
or
ismethoddescriptor
(
object
)
or
ismethodwrapper
(
object
)
or
isinstance
(
object
,
functools
.
_singledispatchmethod_get
))
def
isabstract
(
object
):
"""Return true if the object is an abstract base class (ABC)."""
if
not
isinstance
(
object
,
type
):
return
False
if
object
.
__flags__
&
TPFLAGS_IS_ABSTRACT
:
return
True
if
not
issubclass
(
type
(
object
),
abc
.
ABCMeta
):
return
False
if
hasattr
(
object
,
'__abstractmethods__'
):
# It looks like ABCMeta.__new__ has finished running;
# TPFLAGS_IS_ABSTRACT should have been accurate.
return
False
# It looks like ABCMeta.__new__ has not finished running yet; we're
# probably in __init_subclass__. We'll look for abstractmethods manually.
for
name
,
value
in
object
.
__dict__
.
items
():
if
getattr
(
value
,
"__isabstractmethod__"
,
False
):
return
True
for
base
in
object
.
__bases__
:
for
name
in
getattr
(
base
,
"__abstractmethods__"
, ()):
value
=
getattr
(
object
,
name
,
None
)
if
getattr
(
value
,
"__isabstractmethod__"
,
False
):
return
True
return
False
def
_getmembers
(
object
,
predicate
,
getter
):
results
=
[]
processed
=
set
()
names
=
dir
(
object
)
if
isclass
(
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
:
for
base
in
object
.
__bases__
:
for
k
,
v
in
base
.
__dict__
.
items
():
if
isinstance
(
v
,
types
.
DynamicClassAttribute
):
names
.
append
(
k
)
except
AttributeError
:
pass
else
:
mro
=
()
for
key
in
names
:
# 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
if
key
in
processed
:
raise
AttributeError
except
AttributeError
:
for
base
in
mro
:
if
key
in
base
.
__dict__
:
value
=
base
.
__dict__
[
key
]
break
else
:
# could be a (currently) missing slot member, or a buggy
# __dir__; discard and move on
continue
if
not
predicate
or
predicate
(
value
):
results
.
append
((
key
,
value
))
processed
.
add
(
key
)
results
.
sort
(
key
=
lambda
pair
:
pair
[
0
])
return
results
def
getmembers
(
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
)
def
getmembers_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'
)
def
classify_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
(
cls
for
cls
in
metamro
if
cls
not
in
(
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.
for
base
in
mro
:
for
k
,
v
in
base
.
__dict__
.
items
():
if
isinstance
(
v
,
types
.
DynamicClassAttribute
)
and
v
.
fget
is
not
None
:
names
.
append
(
k
)
result
=
[]
processed
=
set
()
for
name
in
names
:
# 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
if
name
not
in
processed
:
try
:
if
name
==
'__dict__'
:
raise
Exception
(
"__dict__ is special, don't want the proxy"
)
get_obj
=
getattr
(
cls
,
name
)
except
Exception
:
pass
else
:
homecls
=
getattr
(
get_obj
,
"__objclass__"
,
homecls
)
if
homecls
not
in
class_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
for
srch_cls
in
class_bases
:
srch_obj
=
getattr
(
srch_cls
,
name
,
None
)
if
srch_obj
is
get_obj
:
last_cls
=
srch_cls
# then check the metaclasses
for
srch_cls
in
metamro
:
try
:
srch_obj
=
srch_cls
.
__getattr__
(
cls
,
name
)
except
AttributeError
:
continue
if
srch_obj
is
get_obj
:
last_cls
=
srch_cls
if
last_cls
is
not
None
:
homecls
=
last_cls
for
base
in
all_bases
:
if
name
in
base
.
__dict__
:
dict_obj
=
base
.
__dict__
[
name
]
if
homecls
not
in
metamro
:
homecls
=
base
break
if
homecls
is
None
:
# unable to locate the attribute anywhere, most likely due to
# buggy custom __dir__; discard and move on
continue
obj
=
get_obj
if
get_obj
is
not
None
else
dict_obj
# Classify the object or its descriptor.
if
isinstance
(
dict_obj
, (
staticmethod
,
types
.
BuiltinMethodType
)):
kind
=
"static method"
obj
=
dict_obj
elif
isinstance
(
dict_obj
, (
classmethod
,
types
.
ClassMethodDescriptorType
)):
kind
=
"class method"
obj
=
dict_obj
elif
isinstance
(
dict_obj
,
property
):
kind
=
"property"
obj
=
dict_obj
elif
isroutine
(
obj
):
kind
=
"method"
else
:
kind
=
"data"
result
.
append
(
Attribute
(
name
,
kind
,
homecls
,
obj
))
processed
.
add
(
name
)
return
result
# ----------------------------------------------------------- class helpers
def
getmro
(
cls
):
"Return tuple of base classes (including cls) in method resolution order."
return
cls
.
__mro__
# -------------------------------------------------------- function helpers
def
unwrap
(
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
()
while
not
isinstance
(
func
,
type
)
and
hasattr
(
func
,
'__wrapped__'
):
if
stop
is
not
None
and
stop
(
func
):
break
func
=
func
.
__wrapped__
id_func
=
id
(
func
)
if
(
id_func
in
memo
)
or
(
len
(
memo
)
>=
recursion_limit
):
raise
ValueError
(
'wrapper loop when unwrapping {!r}'
.
format
(
f
))
memo
[
id_func
]
=
func
return
func
# -------------------------------------------------- source code extraction
def
indentsize
(
line
):
"""Return the indent size, in spaces, at the start of a line of text."""
expline
=
line
.
expandtabs
()
return
len
(
expline
)
-
len
(
expline
.
lstrip
())
def
_findclass
(
func
):
cls
=
sys
.
modules
.
get
(
func
.
__module__
)
if
cls
is
None
:
return
None
for
name
in
func
.
__qualname__
.
split
(
'.'
)[:
-
1
]:
cls
=
getattr
(
cls
,
name
)
if
not
isclass
(
cls
):
return
None
return
cls
def
_finddoc
(
obj
):
if
isclass
(
obj
):
for
base
in
obj
.
__mro__
:
if
base
is
not
object
:
try
:
doc
=
base
.
__doc__
except
AttributeError
:
continue
if
doc
is
not
None
:
return
doc
return
None
if
ismethod
(
obj
):
name
=
obj
.
__func__
.
__name__
self
=
obj
.
__self__
if
(
isclass
(
self
)
and
getattr
(
getattr
(
self
,
name
,
None
),
'__func__'
)
is
obj
.
__func__
):
# classmethod
cls
=
self
else
:
cls
=
self
.
__class__
elif
isfunction
(
obj
):
name
=
obj
.
__name__
cls
=
_findclass
(
obj
)
if
cls
is
None
or
getattr
(
cls
,
name
)
is
not
obj
:
return
None
elif
isbuiltin
(
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().
elif
isinstance
(
obj
,
property
):
name
=
obj
.
__name__
cls
=
_findclass
(
obj
.
fget
)
if
cls
is
None
or
getattr
(
cls
,
name
)
is
not
obj
:
return
None
elif
ismethoddescriptor
(
obj
)
or
isdatadescriptor
(
obj
):
name
=
obj
.
__name__
cls
=
obj
.
__objclass__
if
getattr
(
cls
,
name
)
is
not
obj
:
return
None
if
ismemberdescriptor
(
obj
):
slots
=
getattr
(
cls
,
'__slots__'
,
None
)
if
isinstance
(
slots
,
dict
)
and
name
in
slots
:
return
slots
[
name
]
else
:
return
None
for
base
in
cls
.
__mro__
:
try
:
doc
=
getattr
(
base
,
name
).
__doc__
except
AttributeError
:
continue
if
doc
is
not
None
:
return
doc
return
None
def
getdoc
(
object
):
"""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."""
try
:
doc
=
object
.
__doc__
except
AttributeError
:
return
None
if
doc
is
None
:
try
:
doc
=
_finddoc
(
object
)
except
(
AttributeError
,
TypeError
):
return
None
if
not
isinstance
(
doc
,
str
):
return
None
return
cleandoc
(
doc
)
def
cleandoc
(
doc
):
"""Clean up indentation from docstrings.
Any whitespace that can be uniformly removed from the second line
onwards is removed."""
lines
=
doc
.
expandtabs
().
split
(
'
\n
'
)
# Find minimum indentation of any non-blank lines after first line.
margin
=
sys
.
maxsize
for
line
in
lines
[
1
:]:
content
=
len
(
line
.
lstrip
(
' '
))
if
content
:
indent
=
len
(
line
)
-
content
margin
=
min
(
margin
,
indent
)
# Remove indentation.
if
lines
:
lines
[
0
]
=
lines
[
0
].
lstrip
(
' '
)
if
margin
<
sys
.
maxsize
:
for
i
in
range
(
1
,
len
(
lines
)):
lines
[
i
]
=
lines
[
i
][
margin
:]
# Remove any trailing or leading blank lines.
while
lines
and
not
lines
[
-
1
]:
lines
.
pop
()
while
lines
and
not
lines
[
0
]:
lines
.
pop
(
0
)
return
'
\n
'
.
join
(
lines
)
def
getfile
(
object
):
"""Work out which source or compiled file an object was defined in."""
if
ismodule
(
object
):
if
getattr
(
object
,
'__file__'
,
None
):
return
object
.
__file__
raise
TypeError
(
'{!r} is a built-in module'
.
format
(
object
))
if
isclass
(
object
):
if
hasattr
(
object
,
'__module__'
):
module
=
sys
.
modules
.
get
(
object
.
__module__
)
if
getattr
(
module
,
'__file__'
,
None
):
return
module
.
__file__
if
object
.
__module__
==
'__main__'
:
raise
OSError
(
'source code not available'
)
raise
TypeError
(
'{!r} is a built-in class'
.
format
(
object
))
if
ismethod
(
object
):
object
=
object
.
__func__
if
isfunction
(
object
):
object
=
object
.
__code__
if
istraceback
(
object
):
object
=
object
.
tb_frame
if
isframe
(
object
):
object
=
object
.
f_code
if
iscode
(
object
):
return
object
.
co_filename
raise
TypeError
(
'module, class, method, function, traceback, frame, or '
'code object was expected, got {}'
.
format
(
type
(
object
).
__name__
))
def
getmodulename
(
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
)
for
suffix
in
importlib
.
machinery
.
all_suffixes
()]
suffixes
.
sort
()
# try longest suffixes first, in case they overlap
for
neglen
,
suffix
in
suffixes
:
if
fname
.
endswith
(
suffix
):
return
fname
[:
neglen
]
return
None
def
getsourcefile
(
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
[:]
if
any
(
filename
.
endswith
(
s
)
for
s
in
all_bytecode_suffixes
):
filename
=
(
os
.
path
.
splitext
(
filename
)[
0
]
+
importlib
.
machinery
.
SOURCE_SUFFIXES
[
0
])
elif
any
(
filename
.
endswith
(
s
)
for
s
in
importlib
.
machinery
.
EXTENSION_SUFFIXES
):
return
None
elif
filename
.
endswith
(
".fwork"
):
# Apple mobile framework markers are another type of non-source file
return
None
# return a filename found in the linecache even if it doesn't exist on disk
if
filename
in
linecache
.
cache
:
return
filename
if
os
.
path
.
exists
(
filename
):
return
filename
# only return a non-existent filename if the module has a PEP 302 loader
module
=
getmodule
(
object
,
filename
)
if
getattr
(
module
,
'__loader__'
,
None
)
is
not
None
:
return
filename
elif
getattr
(
getattr
(
module
,
"__spec__"
,
None
),
"loader"
,
None
)
is
not
None
:
return
filename
def
getabsfile
(
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
_filename
is
None
:
_filename
=
getsourcefile
(
object
)
or
getfile
(
object
)
return
os
.
path
.
normcase
(
os
.
path
.
abspath
(
_filename
))
modulesbyfile
=
{}
_filesbymodname
=
{}
def
getmodule
(
object
,
_filename
=
None
):
"""Return the module an object was defined in, or None if not found."""
if
ismodule
(
object
):
return
object
if
hasattr
(
object
,
'__module__'
):
return
sys
.
modules
.
get
(
object
.
__module__
)
# Try the filename to modulename cache
if
_filename
is
not
None
and
_filename
in
modulesbyfile
:
return
sys
.
modules
.
get
(
modulesbyfile
[
_filename
])
# Try the cache again with the absolute file name
try
:
file
=
getabsfile
(
object
,
_filename
)
except
(
TypeError
,
FileNotFoundError
):
return
None
if
file
in
modulesbyfile
:
return
sys
.
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
for
modname
,
module
in
sys
.
modules
.
copy
().
items
():
if
ismodule
(
module
)
and
hasattr
(
module
,
'__file__'
):
f
=
module
.
__file__
if
f
==
_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__
if
file
in
modulesbyfile
:
return
sys
.
modules
.
get
(
modulesbyfile
[
file
])
# Check the main module
main
=
sys
.
modules
[
'__main__'
]
if
not
hasattr
(
object
,
'__name__'
):
return
None
if
hasattr
(
main
,
object
.
__name__
):
mainobject
=
getattr
(
main
,
object
.
__name__
)
if
mainobject
is
object
:
return
main
# Check builtins
builtin
=
sys
.
modules
[
'builtins'
]
if
hasattr
(
builtin
,
object
.
__name__
):
builtinobject
=
getattr
(
builtin
,
object
.
__name__
)
if
builtinobject
is
object
:
return
builtin
class
ClassFoundException
(
Exception
):
pass
def
findsource
(
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
)
if
file
:
# 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
(
'<'
)
and
file
.
endswith
(
'>'
)))
or
file
.
endswith
(
'.fwork'
):
raise
OSError
(
'source code not available'
)
module
=
getmodule
(
object
,
file
)
if
module
:
lines
=
linecache
.
getlines
(
file
,
module
.
__dict__
)
if
not
lines
and
file
.
startswith
(
'<'
)
and
hasattr
(
object
,
"__code__"
):
lines
=
linecache
.
_getlines_from_code
(
object
.
__code__
)
else
:
lines
=
linecache
.
getlines
(
file
)
if
not
lines
:
raise
OSError
(
'could not get source code'
)
if
ismodule
(
object
):
return
lines
,
0
if
isclass
(
object
):
try
:
lnum
=
vars
(
object
)[
'__firstlineno__'
]
-
1
except
(
TypeError
,
KeyError
):
raise
OSError
(
'source code not available'
)
if
lnum
>=
len
(
lines
):
raise
OSError
(
'lineno is out of bounds'
)
return
lines
,
lnum
if
ismethod
(
object
):
object
=
object
.
__func__
if
isfunction
(
object
):
object
=
object
.
__code__
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL