inspect.py 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145
  1. """Get useful information from live Python objects.
  2. This module encapsulates the interface provided by the internal special
  3. attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
  4. It also provides some help for examining source code and class layout.
  5. Here are some of the useful functions provided by this module:
  6. ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
  7. isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
  8. isroutine() - check object types
  9. getmembers() - get members of an object that satisfy a given condition
  10. getfile(), getsourcefile(), getsource() - find an object's source code
  11. getdoc(), getcomments() - get documentation on an object
  12. getmodule() - determine the module that an object came from
  13. getclasstree() - arrange classes so as to represent their hierarchy
  14. getargvalues(), getcallargs() - get info about function arguments
  15. getfullargspec() - same, with support for Python 3 features
  16. formatargvalues() - format an argument spec
  17. getouterframes(), getinnerframes() - get info about frames
  18. currentframe() - get the current stack frame
  19. stack(), trace() - get info about frames on the stack or in a traceback
  20. signature() - get a Signature object for the callable
  21. """
  22. # This module is in the public domain. No warranties.
  23. __author__ = ('Ka-Ping Yee <ping@lfw.org>',
  24. 'Yury Selivanov <yselivanov@sprymix.com>')
  25. import abc
  26. import dis
  27. import collections.abc
  28. import enum
  29. import importlib.machinery
  30. import itertools
  31. import linecache
  32. import os
  33. import re
  34. import sys
  35. import tokenize
  36. import token
  37. import types
  38. import warnings
  39. import functools
  40. import builtins
  41. from operator import attrgetter
  42. from collections import namedtuple, OrderedDict
  43. # Create constants for the compiler flags in Include/code.h
  44. # We try to get them from dis to avoid duplication
  45. mod_dict = globals()
  46. for k, v in dis.COMPILER_FLAG_NAMES.items():
  47. mod_dict["CO_" + v] = k
  48. # See Include/object.h
  49. TPFLAGS_IS_ABSTRACT = 1 << 20
  50. # ----------------------------------------------------------- type-checking
  51. def ismodule(object):
  52. """Return true if the object is a module.
  53. Module objects provide these attributes:
  54. __cached__ pathname to byte compiled file
  55. __doc__ documentation string
  56. __file__ filename (missing for built-in modules)"""
  57. return isinstance(object, types.ModuleType)
  58. def isclass(object):
  59. """Return true if the object is a class.
  60. Class objects provide these attributes:
  61. __doc__ documentation string
  62. __module__ name of module in which this class was defined"""
  63. return isinstance(object, type)
  64. def ismethod(object):
  65. """Return true if the object is an instance method.
  66. Instance method objects provide these attributes:
  67. __doc__ documentation string
  68. __name__ name with which this method was defined
  69. __func__ function object containing implementation of method
  70. __self__ instance to which this method is bound"""
  71. return isinstance(object, types.MethodType)
  72. def ismethoddescriptor(object):
  73. """Return true if the object is a method descriptor.
  74. But not if ismethod() or isclass() or isfunction() are true.
  75. This is new in Python 2.2, and, for example, is true of int.__add__.
  76. An object passing this test has a __get__ attribute but not a __set__
  77. attribute, but beyond that the set of attributes varies. __name__ is
  78. usually sensible, and __doc__ often is.
  79. Methods implemented via descriptors that also pass one of the other
  80. tests return false from the ismethoddescriptor() test, simply because
  81. the other tests promise more -- you can, e.g., count on having the
  82. __func__ attribute (etc) when an object passes ismethod()."""
  83. if isclass(object) or ismethod(object) or isfunction(object):
  84. # mutual exclusion
  85. return False
  86. tp = type(object)
  87. return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
  88. def isdatadescriptor(object):
  89. """Return true if the object is a data descriptor.
  90. Data descriptors have both a __get__ and a __set__ attribute. Examples are
  91. properties (defined in Python) and getsets and members (defined in C).
  92. Typically, data descriptors will also have __name__ and __doc__ attributes
  93. (properties, getsets, and members have both of these attributes), but this
  94. is not guaranteed."""
  95. if isclass(object) or ismethod(object) or isfunction(object):
  96. # mutual exclusion
  97. return False
  98. tp = type(object)
  99. return hasattr(tp, "__set__") and hasattr(tp, "__get__")
  100. if hasattr(types, 'MemberDescriptorType'):
  101. # CPython and equivalent
  102. def ismemberdescriptor(object):
  103. """Return true if the object is a member descriptor.
  104. Member descriptors are specialized descriptors defined in extension
  105. modules."""
  106. return isinstance(object, types.MemberDescriptorType)
  107. else:
  108. # Other implementations
  109. def ismemberdescriptor(object):
  110. """Return true if the object is a member descriptor.
  111. Member descriptors are specialized descriptors defined in extension
  112. modules."""
  113. return False
  114. if hasattr(types, 'GetSetDescriptorType'):
  115. # CPython and equivalent
  116. def isgetsetdescriptor(object):
  117. """Return true if the object is a getset descriptor.
  118. getset descriptors are specialized descriptors defined in extension
  119. modules."""
  120. return isinstance(object, types.GetSetDescriptorType)
  121. else:
  122. # Other implementations
  123. def isgetsetdescriptor(object):
  124. """Return true if the object is a getset descriptor.
  125. getset descriptors are specialized descriptors defined in extension
  126. modules."""
  127. return False
  128. def isfunction(object):
  129. """Return true if the object is a user-defined function.
  130. Function objects provide these attributes:
  131. __doc__ documentation string
  132. __name__ name with which this function was defined
  133. __code__ code object containing compiled function bytecode
  134. __defaults__ tuple of any default values for arguments
  135. __globals__ global namespace in which this function was defined
  136. __annotations__ dict of parameter annotations
  137. __kwdefaults__ dict of keyword only parameters with defaults"""
  138. return isinstance(object, types.FunctionType)
  139. def isgeneratorfunction(object):
  140. """Return true if the object is a user-defined generator function.
  141. Generator function objects provide the same attributes as functions.
  142. See help(isfunction) for a list of attributes."""
  143. return bool((isfunction(object) or ismethod(object)) and
  144. object.__code__.co_flags & CO_GENERATOR)
  145. def iscoroutinefunction(object):
  146. """Return true if the object is a coroutine function.
  147. Coroutine functions are defined with "async def" syntax.
  148. """
  149. return bool((isfunction(object) or ismethod(object)) and
  150. object.__code__.co_flags & CO_COROUTINE)
  151. def isasyncgenfunction(object):
  152. """Return true if the object is an asynchronous generator function.
  153. Asynchronous generator functions are defined with "async def"
  154. syntax and have "yield" expressions in their body.
  155. """
  156. return bool((isfunction(object) or ismethod(object)) and
  157. object.__code__.co_flags & CO_ASYNC_GENERATOR)
  158. def isasyncgen(object):
  159. """Return true if the object is an asynchronous generator."""
  160. return isinstance(object, types.AsyncGeneratorType)
  161. def isgenerator(object):
  162. """Return true if the object is a generator.
  163. Generator objects provide these attributes:
  164. __iter__ defined to support iteration over container
  165. close raises a new GeneratorExit exception inside the
  166. generator to terminate the iteration
  167. gi_code code object
  168. gi_frame frame object or possibly None once the generator has
  169. been exhausted
  170. gi_running set to 1 when generator is executing, 0 otherwise
  171. next return the next item from the container
  172. send resumes the generator and "sends" a value that becomes
  173. the result of the current yield-expression
  174. throw used to raise an exception inside the generator"""
  175. return isinstance(object, types.GeneratorType)
  176. def iscoroutine(object):
  177. """Return true if the object is a coroutine."""
  178. return isinstance(object, types.CoroutineType)
  179. def isawaitable(object):
  180. """Return true if object can be passed to an ``await`` expression."""
  181. return (isinstance(object, types.CoroutineType) or
  182. isinstance(object, types.GeneratorType) and
  183. bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or
  184. isinstance(object, collections.abc.Awaitable))
  185. def istraceback(object):
  186. """Return true if the object is a traceback.
  187. Traceback objects provide these attributes:
  188. tb_frame frame object at this level
  189. tb_lasti index of last attempted instruction in bytecode
  190. tb_lineno current line number in Python source code
  191. tb_next next inner traceback object (called by this level)"""
  192. return isinstance(object, types.TracebackType)
  193. def isframe(object):
  194. """Return true if the object is a frame object.
  195. Frame objects provide these attributes:
  196. f_back next outer frame object (this frame's caller)
  197. f_builtins built-in namespace seen by this frame
  198. f_code code object being executed in this frame
  199. f_globals global namespace seen by this frame
  200. f_lasti index of last attempted instruction in bytecode
  201. f_lineno current line number in Python source code
  202. f_locals local namespace seen by this frame
  203. f_trace tracing function for this frame, or None"""
  204. return isinstance(object, types.FrameType)
  205. def iscode(object):
  206. """Return true if the object is a code object.
  207. Code objects provide these attributes:
  208. co_argcount number of arguments (not including *, ** args
  209. or keyword only arguments)
  210. co_code string of raw compiled bytecode
  211. co_cellvars tuple of names of cell variables
  212. co_consts tuple of constants used in the bytecode
  213. co_filename name of file in which this code object was created
  214. co_firstlineno number of first line in Python source code
  215. co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
  216. | 16=nested | 32=generator | 64=nofree | 128=coroutine
  217. | 256=iterable_coroutine | 512=async_generator
  218. co_freevars tuple of names of free variables
  219. co_kwonlyargcount number of keyword only arguments (not including ** arg)
  220. co_lnotab encoded mapping of line numbers to bytecode indices
  221. co_name name with which this code object was defined
  222. co_names tuple of names of local variables
  223. co_nlocals number of local variables
  224. co_stacksize virtual machine stack space required
  225. co_varnames tuple of names of arguments and local variables"""
  226. return isinstance(object, types.CodeType)
  227. def isbuiltin(object):
  228. """Return true if the object is a built-in function or method.
  229. Built-in functions and methods provide these attributes:
  230. __doc__ documentation string
  231. __name__ original name of this function or method
  232. __self__ instance to which a method is bound, or None"""
  233. return isinstance(object, types.BuiltinFunctionType)
  234. def isroutine(object):
  235. """Return true if the object is any kind of function or method."""
  236. return (isbuiltin(object)
  237. or isfunction(object)
  238. or ismethod(object)
  239. or ismethoddescriptor(object))
  240. def isabstract(object):
  241. """Return true if the object is an abstract base class (ABC)."""
  242. if not isinstance(object, type):
  243. return False
  244. if object.__flags__ & TPFLAGS_IS_ABSTRACT:
  245. return True
  246. if not issubclass(type(object), abc.ABCMeta):
  247. return False
  248. if hasattr(object, '__abstractmethods__'):
  249. # It looks like ABCMeta.__new__ has finished running;
  250. # TPFLAGS_IS_ABSTRACT should have been accurate.
  251. return False
  252. # It looks like ABCMeta.__new__ has not finished running yet; we're
  253. # probably in __init_subclass__. We'll look for abstractmethods manually.
  254. for name, value in object.__dict__.items():
  255. if getattr(value, "__isabstractmethod__", False):
  256. return True
  257. for base in object.__bases__:
  258. for name in getattr(base, "__abstractmethods__", ()):
  259. value = getattr(object, name, None)
  260. if getattr(value, "__isabstractmethod__", False):
  261. return True
  262. return False
  263. def getmembers(object, predicate=None):
  264. """Return all members of an object as (name, value) pairs sorted by name.
  265. Optionally, only return members that satisfy a given predicate."""
  266. if isclass(object):
  267. mro = (object,) + getmro(object)
  268. else:
  269. mro = ()
  270. results = []
  271. processed = set()
  272. names = dir(object)
  273. # :dd any DynamicClassAttributes to the list of names if object is a class;
  274. # this may result in duplicate entries if, for example, a virtual
  275. # attribute with the same name as a DynamicClassAttribute exists
  276. try:
  277. for base in object.__bases__:
  278. for k, v in base.__dict__.items():
  279. if isinstance(v, types.DynamicClassAttribute):
  280. names.append(k)
  281. except AttributeError:
  282. pass
  283. for key in names:
  284. # First try to get the value via getattr. Some descriptors don't
  285. # like calling their __get__ (see bug #1785), so fall back to
  286. # looking in the __dict__.
  287. try:
  288. value = getattr(object, key)
  289. # handle the duplicate key
  290. if key in processed:
  291. raise AttributeError
  292. except AttributeError:
  293. for base in mro:
  294. if key in base.__dict__:
  295. value = base.__dict__[key]
  296. break
  297. else:
  298. # could be a (currently) missing slot member, or a buggy
  299. # __dir__; discard and move on
  300. continue
  301. if not predicate or predicate(value):
  302. results.append((key, value))
  303. processed.add(key)
  304. results.sort(key=lambda pair: pair[0])
  305. return results
  306. Attribute = namedtuple('Attribute', 'name kind defining_class object')
  307. def classify_class_attrs(cls):
  308. """Return list of attribute-descriptor tuples.
  309. For each name in dir(cls), the return list contains a 4-tuple
  310. with these elements:
  311. 0. The name (a string).
  312. 1. The kind of attribute this is, one of these strings:
  313. 'class method' created via classmethod()
  314. 'static method' created via staticmethod()
  315. 'property' created via property()
  316. 'method' any other flavor of method or descriptor
  317. 'data' not a method
  318. 2. The class which defined this attribute (a class).
  319. 3. The object as obtained by calling getattr; if this fails, or if the
  320. resulting object does not live anywhere in the class' mro (including
  321. metaclasses) then the object is looked up in the defining class's
  322. dict (found by walking the mro).
  323. If one of the items in dir(cls) is stored in the metaclass it will now
  324. be discovered and not have None be listed as the class in which it was
  325. defined. Any items whose home class cannot be discovered are skipped.
  326. """
  327. mro = getmro(cls)
  328. metamro = getmro(type(cls)) # for attributes stored in the metaclass
  329. metamro = tuple(cls for cls in metamro if cls not in (type, object))
  330. class_bases = (cls,) + mro
  331. all_bases = class_bases + metamro
  332. names = dir(cls)
  333. # :dd any DynamicClassAttributes to the list of names;
  334. # this may result in duplicate entries if, for example, a virtual
  335. # attribute with the same name as a DynamicClassAttribute exists.
  336. for base in mro:
  337. for k, v in base.__dict__.items():
  338. if isinstance(v, types.DynamicClassAttribute):
  339. names.append(k)
  340. result = []
  341. processed = set()
  342. for name in names:
  343. # Get the object associated with the name, and where it was defined.
  344. # Normal objects will be looked up with both getattr and directly in
  345. # its class' dict (in case getattr fails [bug #1785], and also to look
  346. # for a docstring).
  347. # For DynamicClassAttributes on the second pass we only look in the
  348. # class's dict.
  349. #
  350. # Getting an obj from the __dict__ sometimes reveals more than
  351. # using getattr. Static and class methods are dramatic examples.
  352. homecls = None
  353. get_obj = None
  354. dict_obj = None
  355. if name not in processed:
  356. try:
  357. if name == '__dict__':
  358. raise Exception("__dict__ is special, don't want the proxy")
  359. get_obj = getattr(cls, name)
  360. except Exception as exc:
  361. pass
  362. else:
  363. homecls = getattr(get_obj, "__objclass__", homecls)
  364. if homecls not in class_bases:
  365. # if the resulting object does not live somewhere in the
  366. # mro, drop it and search the mro manually
  367. homecls = None
  368. last_cls = None
  369. # first look in the classes
  370. for srch_cls in class_bases:
  371. srch_obj = getattr(srch_cls, name, None)
  372. if srch_obj is get_obj:
  373. last_cls = srch_cls
  374. # then check the metaclasses
  375. for srch_cls in metamro:
  376. try:
  377. srch_obj = srch_cls.__getattr__(cls, name)
  378. except AttributeError:
  379. continue
  380. if srch_obj is get_obj:
  381. last_cls = srch_cls
  382. if last_cls is not None:
  383. homecls = last_cls
  384. for base in all_bases:
  385. if name in base.__dict__:
  386. dict_obj = base.__dict__[name]
  387. if homecls not in metamro:
  388. homecls = base
  389. break
  390. if homecls is None:
  391. # unable to locate the attribute anywhere, most likely due to
  392. # buggy custom __dir__; discard and move on
  393. continue
  394. obj = get_obj if get_obj is not None else dict_obj
  395. # Classify the object or its descriptor.
  396. if isinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):
  397. kind = "static method"
  398. obj = dict_obj
  399. elif isinstance(dict_obj, (classmethod, types.ClassMethodDescriptorType)):
  400. kind = "class method"
  401. obj = dict_obj
  402. elif isinstance(dict_obj, property):
  403. kind = "property"
  404. obj = dict_obj
  405. elif isroutine(obj):
  406. kind = "method"
  407. else:
  408. kind = "data"
  409. result.append(Attribute(name, kind, homecls, obj))
  410. processed.add(name)
  411. return result
  412. # ----------------------------------------------------------- class helpers
  413. def getmro(cls):
  414. "Return tuple of base classes (including cls) in method resolution order."
  415. return cls.__mro__
  416. # -------------------------------------------------------- function helpers
  417. def unwrap(func, *, stop=None):
  418. """Get the object wrapped by *func*.
  419. Follows the chain of :attr:`__wrapped__` attributes returning the last
  420. object in the chain.
  421. *stop* is an optional callback accepting an object in the wrapper chain
  422. as its sole argument that allows the unwrapping to be terminated early if
  423. the callback returns a true value. If the callback never returns a true
  424. value, the last object in the chain is returned as usual. For example,
  425. :func:`signature` uses this to stop unwrapping if any object in the
  426. chain has a ``__signature__`` attribute defined.
  427. :exc:`ValueError` is raised if a cycle is encountered.
  428. """
  429. if stop is None:
  430. def _is_wrapper(f):
  431. return hasattr(f, '__wrapped__')
  432. else:
  433. def _is_wrapper(f):
  434. return hasattr(f, '__wrapped__') and not stop(f)
  435. f = func # remember the original func for error reporting
  436. # Memoise by id to tolerate non-hashable objects, but store objects to
  437. # ensure they aren't destroyed, which would allow their IDs to be reused.
  438. memo = {id(f): f}
  439. recursion_limit = sys.getrecursionlimit()
  440. while _is_wrapper(func):
  441. func = func.__wrapped__
  442. id_func = id(func)
  443. if (id_func in memo) or (len(memo) >= recursion_limit):
  444. raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
  445. memo[id_func] = func
  446. return func
  447. # -------------------------------------------------- source code extraction
  448. def indentsize(line):
  449. """Return the indent size, in spaces, at the start of a line of text."""
  450. expline = line.expandtabs()
  451. return len(expline) - len(expline.lstrip())
  452. def _findclass(func):
  453. cls = sys.modules.get(func.__module__)
  454. if cls is None:
  455. return None
  456. for name in func.__qualname__.split('.')[:-1]:
  457. cls = getattr(cls, name)
  458. if not isclass(cls):
  459. return None
  460. return cls
  461. def _finddoc(obj):
  462. if isclass(obj):
  463. for base in obj.__mro__:
  464. if base is not object:
  465. try:
  466. doc = base.__doc__
  467. except AttributeError:
  468. continue
  469. if doc is not None:
  470. return doc
  471. return None
  472. if ismethod(obj):
  473. name = obj.__func__.__name__
  474. self = obj.__self__
  475. if (isclass(self) and
  476. getattr(getattr(self, name, None), '__func__') is obj.__func__):
  477. # classmethod
  478. cls = self
  479. else:
  480. cls = self.__class__
  481. elif isfunction(obj):
  482. name = obj.__name__
  483. cls = _findclass(obj)
  484. if cls is None or getattr(cls, name) is not obj:
  485. return None
  486. elif isbuiltin(obj):
  487. name = obj.__name__
  488. self = obj.__self__
  489. if (isclass(self) and
  490. self.__qualname__ + '.' + name == obj.__qualname__):
  491. # classmethod
  492. cls = self
  493. else:
  494. cls = self.__class__
  495. # Should be tested before isdatadescriptor().
  496. elif isinstance(obj, property):
  497. func = obj.fget
  498. name = func.__name__
  499. cls = _findclass(func)
  500. if cls is None or getattr(cls, name) is not obj:
  501. return None
  502. elif ismethoddescriptor(obj) or isdatadescriptor(obj):
  503. name = obj.__name__
  504. cls = obj.__objclass__
  505. if getattr(cls, name) is not obj:
  506. return None
  507. else:
  508. return None
  509. for base in cls.__mro__:
  510. try:
  511. doc = getattr(base, name).__doc__
  512. except AttributeError:
  513. continue
  514. if doc is not None:
  515. return doc
  516. return None
  517. def getdoc(object):
  518. """Get the documentation string for an object.
  519. All tabs are expanded to spaces. To clean up docstrings that are
  520. indented to line up with blocks of code, any whitespace than can be
  521. uniformly removed from the second line onwards is removed."""
  522. try:
  523. doc = object.__doc__
  524. except AttributeError:
  525. return None
  526. if doc is None:
  527. try:
  528. doc = _finddoc(object)
  529. except (AttributeError, TypeError):
  530. return None
  531. if not isinstance(doc, str):
  532. return None
  533. return cleandoc(doc)
  534. def cleandoc(doc):
  535. """Clean up indentation from docstrings.
  536. Any whitespace that can be uniformly removed from the second line
  537. onwards is removed."""
  538. try:
  539. lines = doc.expandtabs().split('\n')
  540. except UnicodeError:
  541. return None
  542. else:
  543. # Find minimum indentation of any non-blank lines after first line.
  544. margin = sys.maxsize
  545. for line in lines[1:]:
  546. content = len(line.lstrip())
  547. if content:
  548. indent = len(line) - content
  549. margin = min(margin, indent)
  550. # Remove indentation.
  551. if lines:
  552. lines[0] = lines[0].lstrip()
  553. if margin < sys.maxsize:
  554. for i in range(1, len(lines)): lines[i] = lines[i][margin:]
  555. # Remove any trailing or leading blank lines.
  556. while lines and not lines[-1]:
  557. lines.pop()
  558. while lines and not lines[0]:
  559. lines.pop(0)
  560. return '\n'.join(lines)
  561. def getfile(object):
  562. """Work out which source or compiled file an object was defined in."""
  563. if ismodule(object):
  564. if getattr(object, '__file__', None):
  565. return object.__file__
  566. raise TypeError('{!r} is a built-in module'.format(object))
  567. if isclass(object):
  568. if hasattr(object, '__module__'):
  569. module = sys.modules.get(object.__module__)
  570. if getattr(module, '__file__', None):
  571. return module.__file__
  572. raise TypeError('{!r} is a built-in class'.format(object))
  573. if ismethod(object):
  574. object = object.__func__
  575. if isfunction(object):
  576. object = object.__code__
  577. if istraceback(object):
  578. object = object.tb_frame
  579. if isframe(object):
  580. object = object.f_code
  581. if iscode(object):
  582. return object.co_filename
  583. raise TypeError('module, class, method, function, traceback, frame, or '
  584. 'code object was expected, got {}'.format(
  585. type(object).__name__))
  586. def getmodulename(path):
  587. """Return the module name for a given file, or None."""
  588. fname = os.path.basename(path)
  589. # Check for paths that look like an actual module file
  590. suffixes = [(-len(suffix), suffix)
  591. for suffix in importlib.machinery.all_suffixes()]
  592. suffixes.sort() # try longest suffixes first, in case they overlap
  593. for neglen, suffix in suffixes:
  594. if fname.endswith(suffix):
  595. return fname[:neglen]
  596. return None
  597. def getsourcefile(object):
  598. """Return the filename that can be used to locate an object's source.
  599. Return None if no way can be identified to get the source.
  600. """
  601. filename = getfile(object)
  602. all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
  603. all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
  604. if any(filename.endswith(s) for s in all_bytecode_suffixes):
  605. filename = (os.path.splitext(filename)[0] +
  606. importlib.machinery.SOURCE_SUFFIXES[0])
  607. elif any(filename.endswith(s) for s in
  608. importlib.machinery.EXTENSION_SUFFIXES):
  609. return None
  610. if os.path.exists(filename):
  611. return filename
  612. # only return a non-existent filename if the module has a PEP 302 loader
  613. if getattr(getmodule(object, filename), '__loader__', None) is not None:
  614. return filename
  615. # or it is in the linecache
  616. if filename in linecache.cache:
  617. return filename
  618. def getabsfile(object, _filename=None):
  619. """Return an absolute path to the source or compiled file for an object.
  620. The idea is for each object to have a unique origin, so this routine
  621. normalizes the result as much as possible."""
  622. if _filename is None:
  623. _filename = getsourcefile(object) or getfile(object)
  624. return os.path.normcase(os.path.abspath(_filename))
  625. modulesbyfile = {}
  626. _filesbymodname = {}
  627. def getmodule(object, _filename=None):
  628. """Return the module an object was defined in, or None if not found."""
  629. if ismodule(object):
  630. return object
  631. if hasattr(object, '__module__'):
  632. return sys.modules.get(object.__module__)
  633. # Try the filename to modulename cache
  634. if _filename is not None and _filename in modulesbyfile:
  635. return sys.modules.get(modulesbyfile[_filename])
  636. # Try the cache again with the absolute file name
  637. try:
  638. file = getabsfile(object, _filename)
  639. except TypeError:
  640. return None
  641. if file in modulesbyfile:
  642. return sys.modules.get(modulesbyfile[file])
  643. # Update the filename to module name cache and check yet again
  644. # Copy sys.modules in order to cope with changes while iterating
  645. for modname, module in sys.modules.copy().items():
  646. if ismodule(module) and hasattr(module, '__file__'):
  647. f = module.__file__
  648. if f == _filesbymodname.get(modname, None):
  649. # Have already mapped this module, so skip it
  650. continue
  651. _filesbymodname[modname] = f
  652. f = getabsfile(module)
  653. # Always map to the name the module knows itself by
  654. modulesbyfile[f] = modulesbyfile[
  655. os.path.realpath(f)] = module.__name__
  656. if file in modulesbyfile:
  657. return sys.modules.get(modulesbyfile[file])
  658. # Check the main module
  659. main = sys.modules['__main__']
  660. if not hasattr(object, '__name__'):
  661. return None
  662. if hasattr(main, object.__name__):
  663. mainobject = getattr(main, object.__name__)
  664. if mainobject is object:
  665. return main
  666. # Check builtins
  667. builtin = sys.modules['builtins']
  668. if hasattr(builtin, object.__name__):
  669. builtinobject = getattr(builtin, object.__name__)
  670. if builtinobject is object:
  671. return builtin
  672. def findsource(object):
  673. """Return the entire source file and starting line number for an object.
  674. The argument may be a module, class, method, function, traceback, frame,
  675. or code object. The source code is returned as a list of all the lines
  676. in the file and the line number indexes a line in that list. An OSError
  677. is raised if the source code cannot be retrieved."""
  678. file = getsourcefile(object)
  679. if file:
  680. # Invalidate cache if needed.
  681. linecache.checkcache(file)
  682. else:
  683. file = getfile(object)
  684. # Allow filenames in form of "<something>" to pass through.
  685. # `doctest` monkeypatches `linecache` module to enable
  686. # inspection, so let `linecache.getlines` to be called.
  687. if not (file.startswith('<') and file.endswith('>')):
  688. raise OSError('source code not available')
  689. module = getmodule(object, file)
  690. if module:
  691. lines = linecache.getlines(file, module.__dict__)
  692. else:
  693. lines = linecache.getlines(file)
  694. if not lines:
  695. raise OSError('could not get source code')
  696. if ismodule(object):
  697. return lines, 0
  698. if isclass(object):
  699. name = object.__name__
  700. pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
  701. # make some effort to find the best matching class definition:
  702. # use the one with the least indentation, which is the one
  703. # that's most probably not inside a function definition.
  704. candidates = []
  705. for i in range(len(lines)):
  706. match = pat.match(lines[i])
  707. if match:
  708. # if it's at toplevel, it's already the best one
  709. if lines[i][0] == 'c':
  710. return lines, i
  711. # else add whitespace to candidate list
  712. candidates.append((match.group(1), i))
  713. if candidates:
  714. # this will sort by whitespace, and by line number,
  715. # less whitespace first
  716. candidates.sort()
  717. return lines, candidates[0][1]
  718. else:
  719. raise OSError('could not find class definition')
  720. if ismethod(object):
  721. object = object.__func__
  722. if isfunction(object):
  723. object = object.__code__
  724. if istraceback(object):
  725. object = object.tb_frame
  726. if isframe(object):
  727. object = object.f_code
  728. if iscode(object):
  729. if not hasattr(object, 'co_firstlineno'):
  730. raise OSError('could not find function definition')
  731. lnum = object.co_firstlineno - 1
  732. pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
  733. while lnum > 0:
  734. if pat.match(lines[lnum]): break
  735. lnum = lnum - 1
  736. return lines, lnum
  737. raise OSError('could not find code object')
  738. def getcomments(object):
  739. """Get lines of comments immediately preceding an object's source code.
  740. Returns None when source can't be found.
  741. """
  742. try:
  743. lines, lnum = findsource(object)
  744. except (OSError, TypeError):
  745. return None
  746. if ismodule(object):
  747. # Look for a comment block at the top of the file.
  748. start = 0
  749. if lines and lines[0][:2] == '#!': start = 1
  750. while start < len(lines) and lines[start].strip() in ('', '#'):
  751. start = start + 1
  752. if start < len(lines) and lines[start][:1] == '#':
  753. comments = []
  754. end = start
  755. while end < len(lines) and lines[end][:1] == '#':
  756. comments.append(lines[end].expandtabs())
  757. end = end + 1
  758. return ''.join(comments)
  759. # Look for a preceding block of comments at the same indentation.
  760. elif lnum > 0:
  761. indent = indentsize(lines[lnum])
  762. end = lnum - 1
  763. if end >= 0 and lines[end].lstrip()[:1] == '#' and \
  764. indentsize(lines[end]) == indent:
  765. comments = [lines[end].expandtabs().lstrip()]
  766. if end > 0:
  767. end = end - 1
  768. comment = lines[end].expandtabs().lstrip()
  769. while comment[:1] == '#' and indentsize(lines[end]) == indent:
  770. comments[:0] = [comment]
  771. end = end - 1
  772. if end < 0: break
  773. comment = lines[end].expandtabs().lstrip()
  774. while comments and comments[0].strip() == '#':
  775. comments[:1] = []
  776. while comments and comments[-1].strip() == '#':
  777. comments[-1:] = []
  778. return ''.join(comments)
  779. class EndOfBlock(Exception): pass
  780. class BlockFinder:
  781. """Provide a tokeneater() method to detect the end of a code block."""
  782. def __init__(self):
  783. self.indent = 0
  784. self.islambda = False
  785. self.started = False
  786. self.passline = False
  787. self.indecorator = False
  788. self.decoratorhasargs = False
  789. self.last = 1
  790. def tokeneater(self, type, token, srowcol, erowcol, line):
  791. if not self.started and not self.indecorator:
  792. # skip any decorators
  793. if token == "@":
  794. self.indecorator = True
  795. # look for the first "def", "class" or "lambda"
  796. elif token in ("def", "class", "lambda"):
  797. if token == "lambda":
  798. self.islambda = True
  799. self.started = True
  800. self.passline = True # skip to the end of the line
  801. elif token == "(":
  802. if self.indecorator:
  803. self.decoratorhasargs = True
  804. elif token == ")":
  805. if self.indecorator:
  806. self.indecorator = False
  807. self.decoratorhasargs = False
  808. elif type == tokenize.NEWLINE:
  809. self.passline = False # stop skipping when a NEWLINE is seen
  810. self.last = srowcol[0]
  811. if self.islambda: # lambdas always end at the first NEWLINE
  812. raise EndOfBlock
  813. # hitting a NEWLINE when in a decorator without args
  814. # ends the decorator
  815. if self.indecorator and not self.decoratorhasargs:
  816. self.indecorator = False
  817. elif self.passline:
  818. pass
  819. elif type == tokenize.INDENT:
  820. self.indent = self.indent + 1
  821. self.passline = True
  822. elif type == tokenize.DEDENT:
  823. self.indent = self.indent - 1
  824. # the end of matching indent/dedent pairs end a block
  825. # (note that this only works for "def"/"class" blocks,
  826. # not e.g. for "if: else:" or "try: finally:" blocks)
  827. if self.indent <= 0:
  828. raise EndOfBlock
  829. elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
  830. # any other token on the same indentation level end the previous
  831. # block as well, except the pseudo-tokens COMMENT and NL.
  832. raise EndOfBlock
  833. def getblock(lines):
  834. """Extract the block of code at the top of the given list of lines."""
  835. blockfinder = BlockFinder()
  836. try:
  837. tokens = tokenize.generate_tokens(iter(lines).__next__)
  838. for _token in tokens:
  839. blockfinder.tokeneater(*_token)
  840. except (EndOfBlock, IndentationError):
  841. pass
  842. return lines[:blockfinder.last]
  843. def getsourcelines(object):
  844. """Return a list of source lines and starting line number for an object.
  845. The argument may be a module, class, method, function, traceback, frame,
  846. or code object. The source code is returned as a list of the lines
  847. corresponding to the object and the line number indicates where in the
  848. original source file the first line of code was found. An OSError is
  849. raised if the source code cannot be retrieved."""
  850. object = unwrap(object)
  851. lines, lnum = findsource(object)
  852. if istraceback(object):
  853. object = object.tb_frame
  854. # for module or frame that corresponds to module, return all source lines
  855. if (ismodule(object) or
  856. (isframe(object) and object.f_code.co_name == "<module>")):
  857. return lines, 0
  858. else:
  859. return getblock(lines[lnum:]), lnum + 1
  860. def getsource(object):
  861. """Return the text of the source code for an object.
  862. The argument may be a module, class, method, function, traceback, frame,
  863. or code object. The source code is returned as a single string. An
  864. OSError is raised if the source code cannot be retrieved."""
  865. lines, lnum = getsourcelines(object)
  866. return ''.join(lines)
  867. # --------------------------------------------------- class tree extraction
  868. def walktree(classes, children, parent):
  869. """Recursive helper function for getclasstree()."""
  870. results = []
  871. classes.sort(key=attrgetter('__module__', '__name__'))
  872. for c in classes:
  873. results.append((c, c.__bases__))
  874. if c in children:
  875. results.append(walktree(children[c], children, c))
  876. return results
  877. def getclasstree(classes, unique=False):
  878. """Arrange the given list of classes into a hierarchy of nested lists.
  879. Where a nested list appears, it contains classes derived from the class
  880. whose entry immediately precedes the list. Each entry is a 2-tuple
  881. containing a class and a tuple of its base classes. If the 'unique'
  882. argument is true, exactly one entry appears in the returned structure
  883. for each class in the given list. Otherwise, classes using multiple
  884. inheritance and their descendants will appear multiple times."""
  885. children = {}
  886. roots = []
  887. for c in classes:
  888. if c.__bases__:
  889. for parent in c.__bases__:
  890. if not parent in children:
  891. children[parent] = []
  892. if c not in children[parent]:
  893. children[parent].append(c)
  894. if unique and parent in classes: break
  895. elif c not in roots:
  896. roots.append(c)
  897. for parent in children:
  898. if parent not in classes:
  899. roots.append(parent)
  900. return walktree(roots, children, None)
  901. # ------------------------------------------------ argument list extraction
  902. Arguments = namedtuple('Arguments', 'args, varargs, varkw')
  903. def getargs(co):
  904. """Get information about the arguments accepted by a code object.
  905. Three things are returned: (args, varargs, varkw), where
  906. 'args' is the list of argument names. Keyword-only arguments are
  907. appended. 'varargs' and 'varkw' are the names of the * and **
  908. arguments or None."""
  909. args, varargs, kwonlyargs, varkw = _getfullargs(co)
  910. return Arguments(args + kwonlyargs, varargs, varkw)
  911. def _getfullargs(co):
  912. """Get information about the arguments accepted by a code object.
  913. Four things are returned: (args, varargs, kwonlyargs, varkw), where
  914. 'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
  915. and 'varkw' are the names of the * and ** arguments or None."""
  916. if not iscode(co):
  917. raise TypeError('{!r} is not a code object'.format(co))
  918. nargs = co.co_argcount
  919. names = co.co_varnames
  920. nkwargs = co.co_kwonlyargcount
  921. args = list(names[:nargs])
  922. kwonlyargs = list(names[nargs:nargs+nkwargs])
  923. step = 0
  924. nargs += nkwargs
  925. varargs = None
  926. if co.co_flags & CO_VARARGS:
  927. varargs = co.co_varnames[nargs]
  928. nargs = nargs + 1
  929. varkw = None
  930. if co.co_flags & CO_VARKEYWORDS:
  931. varkw = co.co_varnames[nargs]
  932. return args, varargs, kwonlyargs, varkw
  933. ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
  934. def getargspec(func):
  935. """Get the names and default values of a function's parameters.
  936. A tuple of four things is returned: (args, varargs, keywords, defaults).
  937. 'args' is a list of the argument names, including keyword-only argument names.
  938. 'varargs' and 'keywords' are the names of the * and ** parameters or None.
  939. 'defaults' is an n-tuple of the default values of the last n parameters.
  940. This function is deprecated, as it does not support annotations or
  941. keyword-only parameters and will raise ValueError if either is present
  942. on the supplied callable.
  943. For a more structured introspection API, use inspect.signature() instead.
  944. Alternatively, use getfullargspec() for an API with a similar namedtuple
  945. based interface, but full support for annotations and keyword-only
  946. parameters.
  947. Deprecated since Python 3.5, use `inspect.getfullargspec()`.
  948. """
  949. warnings.warn("inspect.getargspec() is deprecated since Python 3.0, "
  950. "use inspect.signature() or inspect.getfullargspec()",
  951. DeprecationWarning, stacklevel=2)
  952. args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
  953. getfullargspec(func)
  954. if kwonlyargs or ann:
  955. raise ValueError("Function has keyword-only parameters or annotations"
  956. ", use getfullargspec() API which can support them")
  957. return ArgSpec(args, varargs, varkw, defaults)
  958. FullArgSpec = namedtuple('FullArgSpec',
  959. 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
  960. def getfullargspec(func):
  961. """Get the names and default values of a callable object's parameters.
  962. A tuple of seven things is returned:
  963. (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
  964. 'args' is a list of the parameter names.
  965. 'varargs' and 'varkw' are the names of the * and ** parameters or None.
  966. 'defaults' is an n-tuple of the default values of the last n parameters.
  967. 'kwonlyargs' is a list of keyword-only parameter names.
  968. 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
  969. 'annotations' is a dictionary mapping parameter names to annotations.
  970. Notable differences from inspect.signature():
  971. - the "self" parameter is always reported, even for bound methods
  972. - wrapper chains defined by __wrapped__ *not* unwrapped automatically
  973. """
  974. try:
  975. # Re: `skip_bound_arg=False`
  976. #
  977. # There is a notable difference in behaviour between getfullargspec
  978. # and Signature: the former always returns 'self' parameter for bound
  979. # methods, whereas the Signature always shows the actual calling
  980. # signature of the passed object.
  981. #
  982. # To simulate this behaviour, we "unbind" bound methods, to trick
  983. # inspect.signature to always return their first parameter ("self",
  984. # usually)
  985. # Re: `follow_wrapper_chains=False`
  986. #
  987. # getfullargspec() historically ignored __wrapped__ attributes,
  988. # so we ensure that remains the case in 3.3+
  989. sig = _signature_from_callable(func,
  990. follow_wrapper_chains=False,
  991. skip_bound_arg=False,
  992. sigcls=Signature)
  993. except Exception as ex:
  994. # Most of the times 'signature' will raise ValueError.
  995. # But, it can also raise AttributeError, and, maybe something
  996. # else. So to be fully backwards compatible, we catch all
  997. # possible exceptions here, and reraise a TypeError.
  998. raise TypeError('unsupported callable') from ex
  999. args = []
  1000. varargs = None
  1001. varkw = None
  1002. kwonlyargs = []
  1003. defaults = ()
  1004. annotations = {}
  1005. defaults = ()
  1006. kwdefaults = {}
  1007. if sig.return_annotation is not sig.empty:
  1008. annotations['return'] = sig.return_annotation
  1009. for param in sig.parameters.values():
  1010. kind = param.kind
  1011. name = param.name
  1012. if kind is _POSITIONAL_ONLY:
  1013. args.append(name)
  1014. elif kind is _POSITIONAL_OR_KEYWORD:
  1015. args.append(name)
  1016. if param.default is not param.empty:
  1017. defaults += (param.default,)
  1018. elif kind is _VAR_POSITIONAL:
  1019. varargs = name
  1020. elif kind is _KEYWORD_ONLY:
  1021. kwonlyargs.append(name)
  1022. if param.default is not param.empty:
  1023. kwdefaults[name] = param.default
  1024. elif kind is _VAR_KEYWORD:
  1025. varkw = name
  1026. if param.annotation is not param.empty:
  1027. annotations[name] = param.annotation
  1028. if not kwdefaults:
  1029. # compatibility with 'func.__kwdefaults__'
  1030. kwdefaults = None
  1031. if not defaults:
  1032. # compatibility with 'func.__defaults__'
  1033. defaults = None
  1034. return FullArgSpec(args, varargs, varkw, defaults,
  1035. kwonlyargs, kwdefaults, annotations)
  1036. ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
  1037. def getargvalues(frame):
  1038. """Get information about arguments passed into a particular frame.
  1039. A tuple of four things is returned: (args, varargs, varkw, locals).
  1040. 'args' is a list of the argument names.
  1041. 'varargs' and 'varkw' are the names of the * and ** arguments or None.
  1042. 'locals' is the locals dictionary of the given frame."""
  1043. args, varargs, varkw = getargs(frame.f_code)
  1044. return ArgInfo(args, varargs, varkw, frame.f_locals)
  1045. def formatannotation(annotation, base_module=None):
  1046. if getattr(annotation, '__module__', None) == 'typing':
  1047. return repr(annotation).replace('typing.', '')
  1048. if isinstance(annotation, type):
  1049. if annotation.__module__ in ('builtins', base_module):
  1050. return annotation.__qualname__
  1051. return annotation.__module__+'.'+annotation.__qualname__
  1052. return repr(annotation)
  1053. def formatannotationrelativeto(object):
  1054. module = getattr(object, '__module__', None)
  1055. def _formatannotation(annotation):
  1056. return formatannotation(annotation, module)
  1057. return _formatannotation
  1058. def formatargspec(args, varargs=None, varkw=None, defaults=None,
  1059. kwonlyargs=(), kwonlydefaults={}, annotations={},
  1060. formatarg=str,
  1061. formatvarargs=lambda name: '*' + name,
  1062. formatvarkw=lambda name: '**' + name,
  1063. formatvalue=lambda value: '=' + repr(value),
  1064. formatreturns=lambda text: ' -> ' + text,
  1065. formatannotation=formatannotation):
  1066. """Format an argument spec from the values returned by getfullargspec.
  1067. The first seven arguments are (args, varargs, varkw, defaults,
  1068. kwonlyargs, kwonlydefaults, annotations). The other five arguments
  1069. are the corresponding optional formatting functions that are called to
  1070. turn names and values into strings. The last argument is an optional
  1071. function to format the sequence of arguments.
  1072. Deprecated since Python 3.5: use the `signature` function and `Signature`
  1073. objects.
  1074. """
  1075. from warnings import warn
  1076. warn("`formatargspec` is deprecated since Python 3.5. Use `signature` and "
  1077. "the `Signature` object directly",
  1078. DeprecationWarning,
  1079. stacklevel=2)
  1080. def formatargandannotation(arg):
  1081. result = formatarg(arg)
  1082. if arg in annotations:
  1083. result += ': ' + formatannotation(annotations[arg])
  1084. return result
  1085. specs = []
  1086. if defaults:
  1087. firstdefault = len(args) - len(defaults)
  1088. for i, arg in enumerate(args):
  1089. spec = formatargandannotation(arg)
  1090. if defaults and i >= firstdefault:
  1091. spec = spec + formatvalue(defaults[i - firstdefault])
  1092. specs.append(spec)
  1093. if varargs is not None:
  1094. specs.append(formatvarargs(formatargandannotation(varargs)))
  1095. else:
  1096. if kwonlyargs:
  1097. specs.append('*')
  1098. if kwonlyargs:
  1099. for kwonlyarg in kwonlyargs:
  1100. spec = formatargandannotation(kwonlyarg)
  1101. if kwonlydefaults and kwonlyarg in kwonlydefaults:
  1102. spec += formatvalue(kwonlydefaults[kwonlyarg])
  1103. specs.append(spec)
  1104. if varkw is not None:
  1105. specs.append(formatvarkw(formatargandannotation(varkw)))
  1106. result = '(' + ', '.join(specs) + ')'
  1107. if 'return' in annotations:
  1108. result += formatreturns(formatannotation(annotations['return']))
  1109. return result
  1110. def formatargvalues(args, varargs, varkw, locals,
  1111. formatarg=str,
  1112. formatvarargs=lambda name: '*' + name,
  1113. formatvarkw=lambda name: '**' + name,
  1114. formatvalue=lambda value: '=' + repr(value)):
  1115. """Format an argument spec from the 4 values returned by getargvalues.
  1116. The first four arguments are (args, varargs, varkw, locals). The
  1117. next four arguments are the corresponding optional formatting functions
  1118. that are called to turn names and values into strings. The ninth
  1119. argument is an optional function to format the sequence of arguments."""
  1120. def convert(name, locals=locals,
  1121. formatarg=formatarg, formatvalue=formatvalue):
  1122. return formatarg(name) + formatvalue(locals[name])
  1123. specs = []
  1124. for i in range(len(args)):
  1125. specs.append(convert(args[i]))
  1126. if varargs:
  1127. specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
  1128. if varkw:
  1129. specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
  1130. return '(' + ', '.join(specs) + ')'
  1131. def _missing_arguments(f_name, argnames, pos, values):
  1132. names = [repr(name) for name in argnames if name not in values]
  1133. missing = len(names)
  1134. if missing == 1:
  1135. s = names[0]
  1136. elif missing == 2:
  1137. s = "{} and {}".format(*names)
  1138. else:
  1139. tail = ", {} and {}".format(*names[-2:])
  1140. del names[-2:]
  1141. s = ", ".join(names) + tail
  1142. raise TypeError("%s() missing %i required %s argument%s: %s" %
  1143. (f_name, missing,
  1144. "positional" if pos else "keyword-only",
  1145. "" if missing == 1 else "s", s))
  1146. def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
  1147. atleast = len(args) - defcount
  1148. kwonly_given = len([arg for arg in kwonly if arg in values])
  1149. if varargs:
  1150. plural = atleast != 1
  1151. sig = "at least %d" % (atleast,)
  1152. elif defcount:
  1153. plural = True
  1154. sig = "from %d to %d" % (atleast, len(args))
  1155. else:
  1156. plural = len(args) != 1
  1157. sig = str(len(args))
  1158. kwonly_sig = ""
  1159. if kwonly_given:
  1160. msg = " positional argument%s (and %d keyword-only argument%s)"
  1161. kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
  1162. "s" if kwonly_given != 1 else ""))
  1163. raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
  1164. (f_name, sig, "s" if plural else "", given, kwonly_sig,
  1165. "was" if given == 1 and not kwonly_given else "were"))
  1166. def getcallargs(*func_and_positional, **named):
  1167. """Get the mapping of arguments to values.
  1168. A dict is returned, with keys the function argument names (including the
  1169. names of the * and ** arguments, if any), and values the respective bound
  1170. values from 'positional' and 'named'."""
  1171. func = func_and_positional[0]
  1172. positional = func_and_positional[1:]
  1173. spec = getfullargspec(func)
  1174. args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
  1175. f_name = func.__name__
  1176. arg2value = {}
  1177. if ismethod(func) and func.__self__ is not None:
  1178. # implicit 'self' (or 'cls' for classmethods) argument
  1179. positional = (func.__self__,) + positional
  1180. num_pos = len(positional)
  1181. num_args = len(args)
  1182. num_defaults = len(defaults) if defaults else 0
  1183. n = min(num_pos, num_args)
  1184. for i in range(n):
  1185. arg2value[args[i]] = positional[i]
  1186. if varargs:
  1187. arg2value[varargs] = tuple(positional[n:])
  1188. possible_kwargs = set(args + kwonlyargs)
  1189. if varkw:
  1190. arg2value[varkw] = {}
  1191. for kw, value in named.items():
  1192. if kw not in possible_kwargs:
  1193. if not varkw:
  1194. raise TypeError("%s() got an unexpected keyword argument %r" %
  1195. (f_name, kw))
  1196. arg2value[varkw][kw] = value
  1197. continue
  1198. if kw in arg2value:
  1199. raise TypeError("%s() got multiple values for argument %r" %
  1200. (f_name, kw))
  1201. arg2value[kw] = value
  1202. if num_pos > num_args and not varargs:
  1203. _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
  1204. num_pos, arg2value)
  1205. if num_pos < num_args:
  1206. req = args[:num_args - num_defaults]
  1207. for arg in req:
  1208. if arg not in arg2value:
  1209. _missing_arguments(f_name, req, True, arg2value)
  1210. for i, arg in enumerate(args[num_args - num_defaults:]):
  1211. if arg not in arg2value:
  1212. arg2value[arg] = defaults[i]
  1213. missing = 0
  1214. for kwarg in kwonlyargs:
  1215. if kwarg not in arg2value:
  1216. if kwonlydefaults and kwarg in kwonlydefaults:
  1217. arg2value[kwarg] = kwonlydefaults[kwarg]
  1218. else:
  1219. missing += 1
  1220. if missing:
  1221. _missing_arguments(f_name, kwonlyargs, False, arg2value)
  1222. return arg2value
  1223. ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
  1224. def getclosurevars(func):
  1225. """
  1226. Get the mapping of free variables to their current values.
  1227. Returns a named tuple of dicts mapping the current nonlocal, global
  1228. and builtin references as seen by the body of the function. A final
  1229. set of unbound names that could not be resolved is also provided.
  1230. """
  1231. if ismethod(func):
  1232. func = func.__func__
  1233. if not isfunction(func):
  1234. raise TypeError("{!r} is not a Python function".format(func))
  1235. code = func.__code__
  1236. # Nonlocal references are named in co_freevars and resolved
  1237. # by looking them up in __closure__ by positional index
  1238. if func.__closure__ is None:
  1239. nonlocal_vars = {}
  1240. else:
  1241. nonlocal_vars = {
  1242. var : cell.cell_contents
  1243. for var, cell in zip(code.co_freevars, func.__closure__)
  1244. }
  1245. # Global and builtin references are named in co_names and resolved
  1246. # by looking them up in __globals__ or __builtins__
  1247. global_ns = func.__globals__
  1248. builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
  1249. if ismodule(builtin_ns):
  1250. builtin_ns = builtin_ns.__dict__
  1251. global_vars = {}
  1252. builtin_vars = {}
  1253. unbound_names = set()
  1254. for name in code.co_names:
  1255. if name in ("None", "True", "False"):
  1256. # Because these used to be builtins instead of keywords, they
  1257. # may still show up as name references. We ignore them.
  1258. continue
  1259. try:
  1260. global_vars[name] = global_ns[name]
  1261. except KeyError:
  1262. try:
  1263. builtin_vars[name] = builtin_ns[name]
  1264. except KeyError:
  1265. unbound_names.add(name)
  1266. return ClosureVars(nonlocal_vars, global_vars,
  1267. builtin_vars, unbound_names)
  1268. # -------------------------------------------------- stack frame extraction
  1269. Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
  1270. def getframeinfo(frame, context=1):
  1271. """Get information about a frame or traceback object.
  1272. A tuple of five things is returned: the filename, the line number of
  1273. the current line, the function name, a list of lines of context from
  1274. the source code, and the index of the current line within that list.
  1275. The optional second argument specifies the number of lines of context
  1276. to return, which are centered around the current line."""
  1277. if istraceback(frame):
  1278. lineno = frame.tb_lineno
  1279. frame = frame.tb_frame
  1280. else:
  1281. lineno = frame.f_lineno
  1282. if not isframe(frame):
  1283. raise TypeError('{!r} is not a frame or traceback object'.format(frame))
  1284. filename = getsourcefile(frame) or getfile(frame)
  1285. if context > 0:
  1286. start = lineno - 1 - context//2
  1287. try:
  1288. lines, lnum = findsource(frame)
  1289. except OSError:
  1290. lines = index = None
  1291. else:
  1292. start = max(0, min(start, len(lines) - context))
  1293. lines = lines[start:start+context]
  1294. index = lineno - 1 - start
  1295. else:
  1296. lines = index = None
  1297. return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
  1298. def getlineno(frame):
  1299. """Get the line number from a frame object, allowing for optimization."""
  1300. # FrameType.f_lineno is now a descriptor that grovels co_lnotab
  1301. return frame.f_lineno
  1302. FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
  1303. def getouterframes(frame, context=1):
  1304. """Get a list of records for a frame and all higher (calling) frames.
  1305. Each record contains a frame object, filename, line number, function
  1306. name, a list of lines of context, and index within the context."""
  1307. framelist = []
  1308. while frame:
  1309. frameinfo = (frame,) + getframeinfo(frame, context)
  1310. framelist.append(FrameInfo(*frameinfo))
  1311. frame = frame.f_back
  1312. return framelist
  1313. def getinnerframes(tb, context=1):
  1314. """Get a list of records for a traceback's frame and all lower frames.
  1315. Each record contains a frame object, filename, line number, function
  1316. name, a list of lines of context, and index within the context."""
  1317. framelist = []
  1318. while tb:
  1319. frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
  1320. framelist.append(FrameInfo(*frameinfo))
  1321. tb = tb.tb_next
  1322. return framelist
  1323. def currentframe():
  1324. """Return the frame of the caller or None if this is not possible."""
  1325. return sys._getframe(1) if hasattr(sys, "_getframe") else None
  1326. def stack(context=1):
  1327. """Return a list of records for the stack above the caller's frame."""
  1328. return getouterframes(sys._getframe(1), context)
  1329. def trace(context=1):
  1330. """Return a list of records for the stack below the current exception."""
  1331. return getinnerframes(sys.exc_info()[2], context)
  1332. # ------------------------------------------------ static version of getattr
  1333. _sentinel = object()
  1334. def _static_getmro(klass):
  1335. return type.__dict__['__mro__'].__get__(klass)
  1336. def _check_instance(obj, attr):
  1337. instance_dict = {}
  1338. try:
  1339. instance_dict = object.__getattribute__(obj, "__dict__")
  1340. except AttributeError:
  1341. pass
  1342. return dict.get(instance_dict, attr, _sentinel)
  1343. def _check_class(klass, attr):
  1344. for entry in _static_getmro(klass):
  1345. if _shadowed_dict(type(entry)) is _sentinel:
  1346. try:
  1347. return entry.__dict__[attr]
  1348. except KeyError:
  1349. pass
  1350. return _sentinel
  1351. def _is_type(obj):
  1352. try:
  1353. _static_getmro(obj)
  1354. except TypeError:
  1355. return False
  1356. return True
  1357. def _shadowed_dict(klass):
  1358. dict_attr = type.__dict__["__dict__"]
  1359. for entry in _static_getmro(klass):
  1360. try:
  1361. class_dict = dict_attr.__get__(entry)["__dict__"]
  1362. except KeyError:
  1363. pass
  1364. else:
  1365. if not (type(class_dict) is types.GetSetDescriptorType and
  1366. class_dict.__name__ == "__dict__" and
  1367. class_dict.__objclass__ is entry):
  1368. return class_dict
  1369. return _sentinel
  1370. def getattr_static(obj, attr, default=_sentinel):
  1371. """Retrieve attributes without triggering dynamic lookup via the
  1372. descriptor protocol, __getattr__ or __getattribute__.
  1373. Note: this function may not be able to retrieve all attributes
  1374. that getattr can fetch (like dynamically created attributes)
  1375. and may find attributes that getattr can't (like descriptors
  1376. that raise AttributeError). It can also return descriptor objects
  1377. instead of instance members in some cases. See the
  1378. documentation for details.
  1379. """
  1380. instance_result = _sentinel
  1381. if not _is_type(obj):
  1382. klass = type(obj)
  1383. dict_attr = _shadowed_dict(klass)
  1384. if (dict_attr is _sentinel or
  1385. type(dict_attr) is types.MemberDescriptorType):
  1386. instance_result = _check_instance(obj, attr)
  1387. else:
  1388. klass = obj
  1389. klass_result = _check_class(klass, attr)
  1390. if instance_result is not _sentinel and klass_result is not _sentinel:
  1391. if (_check_class(type(klass_result), '__get__') is not _sentinel and
  1392. _check_class(type(klass_result), '__set__') is not _sentinel):
  1393. return klass_result
  1394. if instance_result is not _sentinel:
  1395. return instance_result
  1396. if klass_result is not _sentinel:
  1397. return klass_result
  1398. if obj is klass:
  1399. # for types we check the metaclass too
  1400. for entry in _static_getmro(type(klass)):
  1401. if _shadowed_dict(type(entry)) is _sentinel:
  1402. try:
  1403. return entry.__dict__[attr]
  1404. except KeyError:
  1405. pass
  1406. if default is not _sentinel:
  1407. return default
  1408. raise AttributeError(attr)
  1409. # ------------------------------------------------ generator introspection
  1410. GEN_CREATED = 'GEN_CREATED'
  1411. GEN_RUNNING = 'GEN_RUNNING'
  1412. GEN_SUSPENDED = 'GEN_SUSPENDED'
  1413. GEN_CLOSED = 'GEN_CLOSED'
  1414. def getgeneratorstate(generator):
  1415. """Get current state of a generator-iterator.
  1416. Possible states are:
  1417. GEN_CREATED: Waiting to start execution.
  1418. GEN_RUNNING: Currently being executed by the interpreter.
  1419. GEN_SUSPENDED: Currently suspended at a yield expression.
  1420. GEN_CLOSED: Execution has completed.
  1421. """
  1422. if generator.gi_running:
  1423. return GEN_RUNNING
  1424. if generator.gi_frame is None:
  1425. return GEN_CLOSED
  1426. if generator.gi_frame.f_lasti == -1:
  1427. return GEN_CREATED
  1428. return GEN_SUSPENDED
  1429. def getgeneratorlocals(generator):
  1430. """
  1431. Get the mapping of generator local variables to their current values.
  1432. A dict is returned, with the keys the local variable names and values the
  1433. bound values."""
  1434. if not isgenerator(generator):
  1435. raise TypeError("{!r} is not a Python generator".format(generator))
  1436. frame = getattr(generator, "gi_frame", None)
  1437. if frame is not None:
  1438. return generator.gi_frame.f_locals
  1439. else:
  1440. return {}
  1441. # ------------------------------------------------ coroutine introspection
  1442. CORO_CREATED = 'CORO_CREATED'
  1443. CORO_RUNNING = 'CORO_RUNNING'
  1444. CORO_SUSPENDED = 'CORO_SUSPENDED'
  1445. CORO_CLOSED = 'CORO_CLOSED'
  1446. def getcoroutinestate(coroutine):
  1447. """Get current state of a coroutine object.
  1448. Possible states are:
  1449. CORO_CREATED: Waiting to start execution.
  1450. CORO_RUNNING: Currently being executed by the interpreter.
  1451. CORO_SUSPENDED: Currently suspended at an await expression.
  1452. CORO_CLOSED: Execution has completed.
  1453. """
  1454. if coroutine.cr_running:
  1455. return CORO_RUNNING
  1456. if coroutine.cr_frame is None:
  1457. return CORO_CLOSED
  1458. if coroutine.cr_frame.f_lasti == -1:
  1459. return CORO_CREATED
  1460. return CORO_SUSPENDED
  1461. def getcoroutinelocals(coroutine):
  1462. """
  1463. Get the mapping of coroutine local variables to their current values.
  1464. A dict is returned, with the keys the local variable names and values the
  1465. bound values."""
  1466. frame = getattr(coroutine, "cr_frame", None)
  1467. if frame is not None:
  1468. return frame.f_locals
  1469. else:
  1470. return {}
  1471. ###############################################################################
  1472. ### Function Signature Object (PEP 362)
  1473. ###############################################################################
  1474. _WrapperDescriptor = type(type.__call__)
  1475. _MethodWrapper = type(all.__call__)
  1476. _ClassMethodWrapper = type(int.__dict__['from_bytes'])
  1477. _NonUserDefinedCallables = (_WrapperDescriptor,
  1478. _MethodWrapper,
  1479. _ClassMethodWrapper,
  1480. types.BuiltinFunctionType)
  1481. def _signature_get_user_defined_method(cls, method_name):
  1482. """Private helper. Checks if ``cls`` has an attribute
  1483. named ``method_name`` and returns it only if it is a
  1484. pure python function.
  1485. """
  1486. try:
  1487. meth = getattr(cls, method_name)
  1488. except AttributeError:
  1489. return
  1490. else:
  1491. if not isinstance(meth, _NonUserDefinedCallables):
  1492. # Once '__signature__' will be added to 'C'-level
  1493. # callables, this check won't be necessary
  1494. return meth
  1495. def _signature_get_partial(wrapped_sig, partial, extra_args=()):
  1496. """Private helper to calculate how 'wrapped_sig' signature will
  1497. look like after applying a 'functools.partial' object (or alike)
  1498. on it.
  1499. """
  1500. old_params = wrapped_sig.parameters
  1501. new_params = OrderedDict(old_params.items())
  1502. partial_args = partial.args or ()
  1503. partial_keywords = partial.keywords or {}
  1504. if extra_args:
  1505. partial_args = extra_args + partial_args
  1506. try:
  1507. ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
  1508. except TypeError as ex:
  1509. msg = 'partial object {!r} has incorrect arguments'.format(partial)
  1510. raise ValueError(msg) from ex
  1511. transform_to_kwonly = False
  1512. for param_name, param in old_params.items():
  1513. try:
  1514. arg_value = ba.arguments[param_name]
  1515. except KeyError:
  1516. pass
  1517. else:
  1518. if param.kind is _POSITIONAL_ONLY:
  1519. # If positional-only parameter is bound by partial,
  1520. # it effectively disappears from the signature
  1521. new_params.pop(param_name)
  1522. continue
  1523. if param.kind is _POSITIONAL_OR_KEYWORD:
  1524. if param_name in partial_keywords:
  1525. # This means that this parameter, and all parameters
  1526. # after it should be keyword-only (and var-positional
  1527. # should be removed). Here's why. Consider the following
  1528. # function:
  1529. # foo(a, b, *args, c):
  1530. # pass
  1531. #
  1532. # "partial(foo, a='spam')" will have the following
  1533. # signature: "(*, a='spam', b, c)". Because attempting
  1534. # to call that partial with "(10, 20)" arguments will
  1535. # raise a TypeError, saying that "a" argument received
  1536. # multiple values.
  1537. transform_to_kwonly = True
  1538. # Set the new default value
  1539. new_params[param_name] = param.replace(default=arg_value)
  1540. else:
  1541. # was passed as a positional argument
  1542. new_params.pop(param.name)
  1543. continue
  1544. if param.kind is _KEYWORD_ONLY:
  1545. # Set the new default value
  1546. new_params[param_name] = param.replace(default=arg_value)
  1547. if transform_to_kwonly:
  1548. assert param.kind is not _POSITIONAL_ONLY
  1549. if param.kind is _POSITIONAL_OR_KEYWORD:
  1550. new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
  1551. new_params[param_name] = new_param
  1552. new_params.move_to_end(param_name)
  1553. elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
  1554. new_params.move_to_end(param_name)
  1555. elif param.kind is _VAR_POSITIONAL:
  1556. new_params.pop(param.name)
  1557. return wrapped_sig.replace(parameters=new_params.values())
  1558. def _signature_bound_method(sig):
  1559. """Private helper to transform signatures for unbound
  1560. functions to bound methods.
  1561. """
  1562. params = tuple(sig.parameters.values())
  1563. if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
  1564. raise ValueError('invalid method signature')
  1565. kind = params[0].kind
  1566. if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
  1567. # Drop first parameter:
  1568. # '(p1, p2[, ...])' -> '(p2[, ...])'
  1569. params = params[1:]
  1570. else:
  1571. if kind is not _VAR_POSITIONAL:
  1572. # Unless we add a new parameter type we never
  1573. # get here
  1574. raise ValueError('invalid argument type')
  1575. # It's a var-positional parameter.
  1576. # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
  1577. return sig.replace(parameters=params)
  1578. def _signature_is_builtin(obj):
  1579. """Private helper to test if `obj` is a callable that might
  1580. support Argument Clinic's __text_signature__ protocol.
  1581. """
  1582. return (isbuiltin(obj) or
  1583. ismethoddescriptor(obj) or
  1584. isinstance(obj, _NonUserDefinedCallables) or
  1585. # Can't test 'isinstance(type)' here, as it would
  1586. # also be True for regular python classes
  1587. obj in (type, object))
  1588. def _signature_is_functionlike(obj):
  1589. """Private helper to test if `obj` is a duck type of FunctionType.
  1590. A good example of such objects are functions compiled with
  1591. Cython, which have all attributes that a pure Python function
  1592. would have, but have their code statically compiled.
  1593. """
  1594. if not callable(obj) or isclass(obj):
  1595. # All function-like objects are obviously callables,
  1596. # and not classes.
  1597. return False
  1598. name = getattr(obj, '__name__', None)
  1599. code = getattr(obj, '__code__', None)
  1600. defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
  1601. kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
  1602. annotations = getattr(obj, '__annotations__', None)
  1603. return (isinstance(code, types.CodeType) and
  1604. isinstance(name, str) and
  1605. (defaults is None or isinstance(defaults, tuple)) and
  1606. (kwdefaults is None or isinstance(kwdefaults, dict)) and
  1607. isinstance(annotations, dict))
  1608. def _signature_get_bound_param(spec):
  1609. """ Private helper to get first parameter name from a
  1610. __text_signature__ of a builtin method, which should
  1611. be in the following format: '($param1, ...)'.
  1612. Assumptions are that the first argument won't have
  1613. a default value or an annotation.
  1614. """
  1615. assert spec.startswith('($')
  1616. pos = spec.find(',')
  1617. if pos == -1:
  1618. pos = spec.find(')')
  1619. cpos = spec.find(':')
  1620. assert cpos == -1 or cpos > pos
  1621. cpos = spec.find('=')
  1622. assert cpos == -1 or cpos > pos
  1623. return spec[2:pos]
  1624. def _signature_strip_non_python_syntax(signature):
  1625. """
  1626. Private helper function. Takes a signature in Argument Clinic's
  1627. extended signature format.
  1628. Returns a tuple of three things:
  1629. * that signature re-rendered in standard Python syntax,
  1630. * the index of the "self" parameter (generally 0), or None if
  1631. the function does not have a "self" parameter, and
  1632. * the index of the last "positional only" parameter,
  1633. or None if the signature has no positional-only parameters.
  1634. """
  1635. if not signature:
  1636. return signature, None, None
  1637. self_parameter = None
  1638. last_positional_only = None
  1639. lines = [l.encode('ascii') for l in signature.split('\n')]
  1640. generator = iter(lines).__next__
  1641. token_stream = tokenize.tokenize(generator)
  1642. delayed_comma = False
  1643. skip_next_comma = False
  1644. text = []
  1645. add = text.append
  1646. current_parameter = 0
  1647. OP = token.OP
  1648. ERRORTOKEN = token.ERRORTOKEN
  1649. # token stream always starts with ENCODING token, skip it
  1650. t = next(token_stream)
  1651. assert t.type == tokenize.ENCODING
  1652. for t in token_stream:
  1653. type, string = t.type, t.string
  1654. if type == OP:
  1655. if string == ',':
  1656. if skip_next_comma:
  1657. skip_next_comma = False
  1658. else:
  1659. assert not delayed_comma
  1660. delayed_comma = True
  1661. current_parameter += 1
  1662. continue
  1663. if string == '/':
  1664. assert not skip_next_comma
  1665. assert last_positional_only is None
  1666. skip_next_comma = True
  1667. last_positional_only = current_parameter - 1
  1668. continue
  1669. if (type == ERRORTOKEN) and (string == '$'):
  1670. assert self_parameter is None
  1671. self_parameter = current_parameter
  1672. continue
  1673. if delayed_comma:
  1674. delayed_comma = False
  1675. if not ((type == OP) and (string == ')')):
  1676. add(', ')
  1677. add(string)
  1678. if (string == ','):
  1679. add(' ')
  1680. clean_signature = ''.join(text)
  1681. return clean_signature, self_parameter, last_positional_only
  1682. def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
  1683. """Private helper to parse content of '__text_signature__'
  1684. and return a Signature based on it.
  1685. """
  1686. # Lazy import ast because it's relatively heavy and
  1687. # it's not used for other than this function.
  1688. import ast
  1689. Parameter = cls._parameter_cls
  1690. clean_signature, self_parameter, last_positional_only = \
  1691. _signature_strip_non_python_syntax(s)
  1692. program = "def foo" + clean_signature + ": pass"
  1693. try:
  1694. module = ast.parse(program)
  1695. except SyntaxError:
  1696. module = None
  1697. if not isinstance(module, ast.Module):
  1698. raise ValueError("{!r} builtin has invalid signature".format(obj))
  1699. f = module.body[0]
  1700. parameters = []
  1701. empty = Parameter.empty
  1702. invalid = object()
  1703. module = None
  1704. module_dict = {}
  1705. module_name = getattr(obj, '__module__', None)
  1706. if module_name:
  1707. module = sys.modules.get(module_name, None)
  1708. if module:
  1709. module_dict = module.__dict__
  1710. sys_module_dict = sys.modules.copy()
  1711. def parse_name(node):
  1712. assert isinstance(node, ast.arg)
  1713. if node.annotation != None:
  1714. raise ValueError("Annotations are not currently supported")
  1715. return node.arg
  1716. def wrap_value(s):
  1717. try:
  1718. value = eval(s, module_dict)
  1719. except NameError:
  1720. try:
  1721. value = eval(s, sys_module_dict)
  1722. except NameError:
  1723. raise RuntimeError()
  1724. if isinstance(value, str):
  1725. return ast.Str(value)
  1726. if isinstance(value, (int, float)):
  1727. return ast.Num(value)
  1728. if isinstance(value, bytes):
  1729. return ast.Bytes(value)
  1730. if value in (True, False, None):
  1731. return ast.NameConstant(value)
  1732. raise RuntimeError()
  1733. class RewriteSymbolics(ast.NodeTransformer):
  1734. def visit_Attribute(self, node):
  1735. a = []
  1736. n = node
  1737. while isinstance(n, ast.Attribute):
  1738. a.append(n.attr)
  1739. n = n.value
  1740. if not isinstance(n, ast.Name):
  1741. raise RuntimeError()
  1742. a.append(n.id)
  1743. value = ".".join(reversed(a))
  1744. return wrap_value(value)
  1745. def visit_Name(self, node):
  1746. if not isinstance(node.ctx, ast.Load):
  1747. raise ValueError()
  1748. return wrap_value(node.id)
  1749. def p(name_node, default_node, default=empty):
  1750. name = parse_name(name_node)
  1751. if name is invalid:
  1752. return None
  1753. if default_node and default_node is not _empty:
  1754. try:
  1755. default_node = RewriteSymbolics().visit(default_node)
  1756. o = ast.literal_eval(default_node)
  1757. except ValueError:
  1758. o = invalid
  1759. if o is invalid:
  1760. return None
  1761. default = o if o is not invalid else default
  1762. parameters.append(Parameter(name, kind, default=default, annotation=empty))
  1763. # non-keyword-only parameters
  1764. args = reversed(f.args.args)
  1765. defaults = reversed(f.args.defaults)
  1766. iter = itertools.zip_longest(args, defaults, fillvalue=None)
  1767. if last_positional_only is not None:
  1768. kind = Parameter.POSITIONAL_ONLY
  1769. else:
  1770. kind = Parameter.POSITIONAL_OR_KEYWORD
  1771. for i, (name, default) in enumerate(reversed(list(iter))):
  1772. p(name, default)
  1773. if i == last_positional_only:
  1774. kind = Parameter.POSITIONAL_OR_KEYWORD
  1775. # *args
  1776. if f.args.vararg:
  1777. kind = Parameter.VAR_POSITIONAL
  1778. p(f.args.vararg, empty)
  1779. # keyword-only arguments
  1780. kind = Parameter.KEYWORD_ONLY
  1781. for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
  1782. p(name, default)
  1783. # **kwargs
  1784. if f.args.kwarg:
  1785. kind = Parameter.VAR_KEYWORD
  1786. p(f.args.kwarg, empty)
  1787. if self_parameter is not None:
  1788. # Possibly strip the bound argument:
  1789. # - We *always* strip first bound argument if
  1790. # it is a module.
  1791. # - We don't strip first bound argument if
  1792. # skip_bound_arg is False.
  1793. assert parameters
  1794. _self = getattr(obj, '__self__', None)
  1795. self_isbound = _self is not None
  1796. self_ismodule = ismodule(_self)
  1797. if self_isbound and (self_ismodule or skip_bound_arg):
  1798. parameters.pop(0)
  1799. else:
  1800. # for builtins, self parameter is always positional-only!
  1801. p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
  1802. parameters[0] = p
  1803. return cls(parameters, return_annotation=cls.empty)
  1804. def _signature_from_builtin(cls, func, skip_bound_arg=True):
  1805. """Private helper function to get signature for
  1806. builtin callables.
  1807. """
  1808. if not _signature_is_builtin(func):
  1809. raise TypeError("{!r} is not a Python builtin "
  1810. "function".format(func))
  1811. s = getattr(func, "__text_signature__", None)
  1812. if not s:
  1813. raise ValueError("no signature found for builtin {!r}".format(func))
  1814. return _signature_fromstr(cls, func, s, skip_bound_arg)
  1815. def _signature_from_function(cls, func):
  1816. """Private helper: constructs Signature for the given python function."""
  1817. is_duck_function = False
  1818. if not isfunction(func):
  1819. if _signature_is_functionlike(func):
  1820. is_duck_function = True
  1821. else:
  1822. # If it's not a pure Python function, and not a duck type
  1823. # of pure function:
  1824. raise TypeError('{!r} is not a Python function'.format(func))
  1825. Parameter = cls._parameter_cls
  1826. # Parameter information.
  1827. func_code = func.__code__
  1828. pos_count = func_code.co_argcount
  1829. arg_names = func_code.co_varnames
  1830. positional = tuple(arg_names[:pos_count])
  1831. keyword_only_count = func_code.co_kwonlyargcount
  1832. keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
  1833. annotations = func.__annotations__
  1834. defaults = func.__defaults__
  1835. kwdefaults = func.__kwdefaults__
  1836. if defaults:
  1837. pos_default_count = len(defaults)
  1838. else:
  1839. pos_default_count = 0
  1840. parameters = []
  1841. # Non-keyword-only parameters w/o defaults.
  1842. non_default_count = pos_count - pos_default_count
  1843. for name in positional[:non_default_count]:
  1844. annotation = annotations.get(name, _empty)
  1845. parameters.append(Parameter(name, annotation=annotation,
  1846. kind=_POSITIONAL_OR_KEYWORD))
  1847. # ... w/ defaults.
  1848. for offset, name in enumerate(positional[non_default_count:]):
  1849. annotation = annotations.get(name, _empty)
  1850. parameters.append(Parameter(name, annotation=annotation,
  1851. kind=_POSITIONAL_OR_KEYWORD,
  1852. default=defaults[offset]))
  1853. # *args
  1854. if func_code.co_flags & CO_VARARGS:
  1855. name = arg_names[pos_count + keyword_only_count]
  1856. annotation = annotations.get(name, _empty)
  1857. parameters.append(Parameter(name, annotation=annotation,
  1858. kind=_VAR_POSITIONAL))
  1859. # Keyword-only parameters.
  1860. for name in keyword_only:
  1861. default = _empty
  1862. if kwdefaults is not None:
  1863. default = kwdefaults.get(name, _empty)
  1864. annotation = annotations.get(name, _empty)
  1865. parameters.append(Parameter(name, annotation=annotation,
  1866. kind=_KEYWORD_ONLY,
  1867. default=default))
  1868. # **kwargs
  1869. if func_code.co_flags & CO_VARKEYWORDS:
  1870. index = pos_count + keyword_only_count
  1871. if func_code.co_flags & CO_VARARGS:
  1872. index += 1
  1873. name = arg_names[index]
  1874. annotation = annotations.get(name, _empty)
  1875. parameters.append(Parameter(name, annotation=annotation,
  1876. kind=_VAR_KEYWORD))
  1877. # Is 'func' is a pure Python function - don't validate the
  1878. # parameters list (for correct order and defaults), it should be OK.
  1879. return cls(parameters,
  1880. return_annotation=annotations.get('return', _empty),
  1881. __validate_parameters__=is_duck_function)
  1882. def _signature_from_callable(obj, *,
  1883. follow_wrapper_chains=True,
  1884. skip_bound_arg=True,
  1885. sigcls):
  1886. """Private helper function to get signature for arbitrary
  1887. callable objects.
  1888. """
  1889. if not callable(obj):
  1890. raise TypeError('{!r} is not a callable object'.format(obj))
  1891. if isinstance(obj, types.MethodType):
  1892. # In this case we skip the first parameter of the underlying
  1893. # function (usually `self` or `cls`).
  1894. sig = _signature_from_callable(
  1895. obj.__func__,
  1896. follow_wrapper_chains=follow_wrapper_chains,
  1897. skip_bound_arg=skip_bound_arg,
  1898. sigcls=sigcls)
  1899. if skip_bound_arg:
  1900. return _signature_bound_method(sig)
  1901. else:
  1902. return sig
  1903. # Was this function wrapped by a decorator?
  1904. if follow_wrapper_chains:
  1905. obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
  1906. if isinstance(obj, types.MethodType):
  1907. # If the unwrapped object is a *method*, we might want to
  1908. # skip its first parameter (self).
  1909. # See test_signature_wrapped_bound_method for details.
  1910. return _signature_from_callable(
  1911. obj,
  1912. follow_wrapper_chains=follow_wrapper_chains,
  1913. skip_bound_arg=skip_bound_arg,
  1914. sigcls=sigcls)
  1915. try:
  1916. sig = obj.__signature__
  1917. except AttributeError:
  1918. pass
  1919. else:
  1920. if sig is not None:
  1921. if not isinstance(sig, Signature):
  1922. raise TypeError(
  1923. 'unexpected object {!r} in __signature__ '
  1924. 'attribute'.format(sig))
  1925. return sig
  1926. try:
  1927. partialmethod = obj._partialmethod
  1928. except AttributeError:
  1929. pass
  1930. else:
  1931. if isinstance(partialmethod, functools.partialmethod):
  1932. # Unbound partialmethod (see functools.partialmethod)
  1933. # This means, that we need to calculate the signature
  1934. # as if it's a regular partial object, but taking into
  1935. # account that the first positional argument
  1936. # (usually `self`, or `cls`) will not be passed
  1937. # automatically (as for boundmethods)
  1938. wrapped_sig = _signature_from_callable(
  1939. partialmethod.func,
  1940. follow_wrapper_chains=follow_wrapper_chains,
  1941. skip_bound_arg=skip_bound_arg,
  1942. sigcls=sigcls)
  1943. sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
  1944. first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
  1945. if first_wrapped_param.kind is Parameter.VAR_POSITIONAL:
  1946. # First argument of the wrapped callable is `*args`, as in
  1947. # `partialmethod(lambda *args)`.
  1948. return sig
  1949. else:
  1950. sig_params = tuple(sig.parameters.values())
  1951. assert (not sig_params or
  1952. first_wrapped_param is not sig_params[0])
  1953. new_params = (first_wrapped_param,) + sig_params
  1954. return sig.replace(parameters=new_params)
  1955. if isfunction(obj) or _signature_is_functionlike(obj):
  1956. # If it's a pure Python function, or an object that is duck type
  1957. # of a Python function (Cython functions, for instance), then:
  1958. return _signature_from_function(sigcls, obj)
  1959. if _signature_is_builtin(obj):
  1960. return _signature_from_builtin(sigcls, obj,
  1961. skip_bound_arg=skip_bound_arg)
  1962. if isinstance(obj, functools.partial):
  1963. wrapped_sig = _signature_from_callable(
  1964. obj.func,
  1965. follow_wrapper_chains=follow_wrapper_chains,
  1966. skip_bound_arg=skip_bound_arg,
  1967. sigcls=sigcls)
  1968. return _signature_get_partial(wrapped_sig, obj)
  1969. sig = None
  1970. if isinstance(obj, type):
  1971. # obj is a class or a metaclass
  1972. # First, let's see if it has an overloaded __call__ defined
  1973. # in its metaclass
  1974. call = _signature_get_user_defined_method(type(obj), '__call__')
  1975. if call is not None:
  1976. sig = _signature_from_callable(
  1977. call,
  1978. follow_wrapper_chains=follow_wrapper_chains,
  1979. skip_bound_arg=skip_bound_arg,
  1980. sigcls=sigcls)
  1981. else:
  1982. # Now we check if the 'obj' class has a '__new__' method
  1983. new = _signature_get_user_defined_method(obj, '__new__')
  1984. if new is not None:
  1985. sig = _signature_from_callable(
  1986. new,
  1987. follow_wrapper_chains=follow_wrapper_chains,
  1988. skip_bound_arg=skip_bound_arg,
  1989. sigcls=sigcls)
  1990. else:
  1991. # Finally, we should have at least __init__ implemented
  1992. init = _signature_get_user_defined_method(obj, '__init__')
  1993. if init is not None:
  1994. sig = _signature_from_callable(
  1995. init,
  1996. follow_wrapper_chains=follow_wrapper_chains,
  1997. skip_bound_arg=skip_bound_arg,
  1998. sigcls=sigcls)
  1999. if sig is None:
  2000. # At this point we know, that `obj` is a class, with no user-
  2001. # defined '__init__', '__new__', or class-level '__call__'
  2002. for base in obj.__mro__[:-1]:
  2003. # Since '__text_signature__' is implemented as a
  2004. # descriptor that extracts text signature from the
  2005. # class docstring, if 'obj' is derived from a builtin
  2006. # class, its own '__text_signature__' may be 'None'.
  2007. # Therefore, we go through the MRO (except the last
  2008. # class in there, which is 'object') to find the first
  2009. # class with non-empty text signature.
  2010. try:
  2011. text_sig = base.__text_signature__
  2012. except AttributeError:
  2013. pass
  2014. else:
  2015. if text_sig:
  2016. # If 'obj' class has a __text_signature__ attribute:
  2017. # return a signature based on it
  2018. return _signature_fromstr(sigcls, obj, text_sig)
  2019. # No '__text_signature__' was found for the 'obj' class.
  2020. # Last option is to check if its '__init__' is
  2021. # object.__init__ or type.__init__.
  2022. if type not in obj.__mro__:
  2023. # We have a class (not metaclass), but no user-defined
  2024. # __init__ or __new__ for it
  2025. if (obj.__init__ is object.__init__ and
  2026. obj.__new__ is object.__new__):
  2027. # Return a signature of 'object' builtin.
  2028. return sigcls.from_callable(object)
  2029. else:
  2030. raise ValueError(
  2031. 'no signature found for builtin type {!r}'.format(obj))
  2032. elif not isinstance(obj, _NonUserDefinedCallables):
  2033. # An object with __call__
  2034. # We also check that the 'obj' is not an instance of
  2035. # _WrapperDescriptor or _MethodWrapper to avoid
  2036. # infinite recursion (and even potential segfault)
  2037. call = _signature_get_user_defined_method(type(obj), '__call__')
  2038. if call is not None:
  2039. try:
  2040. sig = _signature_from_callable(
  2041. call,
  2042. follow_wrapper_chains=follow_wrapper_chains,
  2043. skip_bound_arg=skip_bound_arg,
  2044. sigcls=sigcls)
  2045. except ValueError as ex:
  2046. msg = 'no signature found for {!r}'.format(obj)
  2047. raise ValueError(msg) from ex
  2048. if sig is not None:
  2049. # For classes and objects we skip the first parameter of their
  2050. # __call__, __new__, or __init__ methods
  2051. if skip_bound_arg:
  2052. return _signature_bound_method(sig)
  2053. else:
  2054. return sig
  2055. if isinstance(obj, types.BuiltinFunctionType):
  2056. # Raise a nicer error message for builtins
  2057. msg = 'no signature found for builtin function {!r}'.format(obj)
  2058. raise ValueError(msg)
  2059. raise ValueError('callable {!r} is not supported by signature'.format(obj))
  2060. class _void:
  2061. """A private marker - used in Parameter & Signature."""
  2062. class _empty:
  2063. """Marker object for Signature.empty and Parameter.empty."""
  2064. class _ParameterKind(enum.IntEnum):
  2065. POSITIONAL_ONLY = 0
  2066. POSITIONAL_OR_KEYWORD = 1
  2067. VAR_POSITIONAL = 2
  2068. KEYWORD_ONLY = 3
  2069. VAR_KEYWORD = 4
  2070. def __str__(self):
  2071. return self._name_
  2072. _POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
  2073. _POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
  2074. _VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
  2075. _KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
  2076. _VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
  2077. _PARAM_NAME_MAPPING = {
  2078. _POSITIONAL_ONLY: 'positional-only',
  2079. _POSITIONAL_OR_KEYWORD: 'positional or keyword',
  2080. _VAR_POSITIONAL: 'variadic positional',
  2081. _KEYWORD_ONLY: 'keyword-only',
  2082. _VAR_KEYWORD: 'variadic keyword'
  2083. }
  2084. _get_paramkind_descr = _PARAM_NAME_MAPPING.__getitem__
  2085. class Parameter:
  2086. """Represents a parameter in a function signature.
  2087. Has the following public attributes:
  2088. * name : str
  2089. The name of the parameter as a string.
  2090. * default : object
  2091. The default value for the parameter if specified. If the
  2092. parameter has no default value, this attribute is set to
  2093. `Parameter.empty`.
  2094. * annotation
  2095. The annotation for the parameter if specified. If the
  2096. parameter has no annotation, this attribute is set to
  2097. `Parameter.empty`.
  2098. * kind : str
  2099. Describes how argument values are bound to the parameter.
  2100. Possible values: `Parameter.POSITIONAL_ONLY`,
  2101. `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
  2102. `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
  2103. """
  2104. __slots__ = ('_name', '_kind', '_default', '_annotation')
  2105. POSITIONAL_ONLY = _POSITIONAL_ONLY
  2106. POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
  2107. VAR_POSITIONAL = _VAR_POSITIONAL
  2108. KEYWORD_ONLY = _KEYWORD_ONLY
  2109. VAR_KEYWORD = _VAR_KEYWORD
  2110. empty = _empty
  2111. def __init__(self, name, kind, *, default=_empty, annotation=_empty):
  2112. try:
  2113. self._kind = _ParameterKind(kind)
  2114. except ValueError:
  2115. raise ValueError(f'value {kind!r} is not a valid Parameter.kind')
  2116. if default is not _empty:
  2117. if self._kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
  2118. msg = '{} parameters cannot have default values'
  2119. msg = msg.format(_get_paramkind_descr(self._kind))
  2120. raise ValueError(msg)
  2121. self._default = default
  2122. self._annotation = annotation
  2123. if name is _empty:
  2124. raise ValueError('name is a required attribute for Parameter')
  2125. if not isinstance(name, str):
  2126. msg = 'name must be a str, not a {}'.format(type(name).__name__)
  2127. raise TypeError(msg)
  2128. if name[0] == '.' and name[1:].isdigit():
  2129. # These are implicit arguments generated by comprehensions. In
  2130. # order to provide a friendlier interface to users, we recast
  2131. # their name as "implicitN" and treat them as positional-only.
  2132. # See issue 19611.
  2133. if self._kind != _POSITIONAL_OR_KEYWORD:
  2134. msg = (
  2135. 'implicit arguments must be passed as '
  2136. 'positional or keyword arguments, not {}'
  2137. )
  2138. msg = msg.format(_get_paramkind_descr(self._kind))
  2139. raise ValueError(msg)
  2140. self._kind = _POSITIONAL_ONLY
  2141. name = 'implicit{}'.format(name[1:])
  2142. if not name.isidentifier():
  2143. raise ValueError('{!r} is not a valid parameter name'.format(name))
  2144. self._name = name
  2145. def __reduce__(self):
  2146. return (type(self),
  2147. (self._name, self._kind),
  2148. {'_default': self._default,
  2149. '_annotation': self._annotation})
  2150. def __setstate__(self, state):
  2151. self._default = state['_default']
  2152. self._annotation = state['_annotation']
  2153. @property
  2154. def name(self):
  2155. return self._name
  2156. @property
  2157. def default(self):
  2158. return self._default
  2159. @property
  2160. def annotation(self):
  2161. return self._annotation
  2162. @property
  2163. def kind(self):
  2164. return self._kind
  2165. def replace(self, *, name=_void, kind=_void,
  2166. annotation=_void, default=_void):
  2167. """Creates a customized copy of the Parameter."""
  2168. if name is _void:
  2169. name = self._name
  2170. if kind is _void:
  2171. kind = self._kind
  2172. if annotation is _void:
  2173. annotation = self._annotation
  2174. if default is _void:
  2175. default = self._default
  2176. return type(self)(name, kind, default=default, annotation=annotation)
  2177. def __str__(self):
  2178. kind = self.kind
  2179. formatted = self._name
  2180. # Add annotation and default value
  2181. if self._annotation is not _empty:
  2182. formatted = '{}: {}'.format(formatted,
  2183. formatannotation(self._annotation))
  2184. if self._default is not _empty:
  2185. if self._annotation is not _empty:
  2186. formatted = '{} = {}'.format(formatted, repr(self._default))
  2187. else:
  2188. formatted = '{}={}'.format(formatted, repr(self._default))
  2189. if kind == _VAR_POSITIONAL:
  2190. formatted = '*' + formatted
  2191. elif kind == _VAR_KEYWORD:
  2192. formatted = '**' + formatted
  2193. return formatted
  2194. def __repr__(self):
  2195. return '<{} "{}">'.format(self.__class__.__name__, self)
  2196. def __hash__(self):
  2197. return hash((self.name, self.kind, self.annotation, self.default))
  2198. def __eq__(self, other):
  2199. if self is other:
  2200. return True
  2201. if not isinstance(other, Parameter):
  2202. return NotImplemented
  2203. return (self._name == other._name and
  2204. self._kind == other._kind and
  2205. self._default == other._default and
  2206. self._annotation == other._annotation)
  2207. class BoundArguments:
  2208. """Result of `Signature.bind` call. Holds the mapping of arguments
  2209. to the function's parameters.
  2210. Has the following public attributes:
  2211. * arguments : OrderedDict
  2212. An ordered mutable mapping of parameters' names to arguments' values.
  2213. Does not contain arguments' default values.
  2214. * signature : Signature
  2215. The Signature object that created this instance.
  2216. * args : tuple
  2217. Tuple of positional arguments values.
  2218. * kwargs : dict
  2219. Dict of keyword arguments values.
  2220. """
  2221. __slots__ = ('arguments', '_signature', '__weakref__')
  2222. def __init__(self, signature, arguments):
  2223. self.arguments = arguments
  2224. self._signature = signature
  2225. @property
  2226. def signature(self):
  2227. return self._signature
  2228. @property
  2229. def args(self):
  2230. args = []
  2231. for param_name, param in self._signature.parameters.items():
  2232. if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
  2233. break
  2234. try:
  2235. arg = self.arguments[param_name]
  2236. except KeyError:
  2237. # We're done here. Other arguments
  2238. # will be mapped in 'BoundArguments.kwargs'
  2239. break
  2240. else:
  2241. if param.kind == _VAR_POSITIONAL:
  2242. # *args
  2243. args.extend(arg)
  2244. else:
  2245. # plain argument
  2246. args.append(arg)
  2247. return tuple(args)
  2248. @property
  2249. def kwargs(self):
  2250. kwargs = {}
  2251. kwargs_started = False
  2252. for param_name, param in self._signature.parameters.items():
  2253. if not kwargs_started:
  2254. if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
  2255. kwargs_started = True
  2256. else:
  2257. if param_name not in self.arguments:
  2258. kwargs_started = True
  2259. continue
  2260. if not kwargs_started:
  2261. continue
  2262. try:
  2263. arg = self.arguments[param_name]
  2264. except KeyError:
  2265. pass
  2266. else:
  2267. if param.kind == _VAR_KEYWORD:
  2268. # **kwargs
  2269. kwargs.update(arg)
  2270. else:
  2271. # plain keyword argument
  2272. kwargs[param_name] = arg
  2273. return kwargs
  2274. def apply_defaults(self):
  2275. """Set default values for missing arguments.
  2276. For variable-positional arguments (*args) the default is an
  2277. empty tuple.
  2278. For variable-keyword arguments (**kwargs) the default is an
  2279. empty dict.
  2280. """
  2281. arguments = self.arguments
  2282. new_arguments = []
  2283. for name, param in self._signature.parameters.items():
  2284. try:
  2285. new_arguments.append((name, arguments[name]))
  2286. except KeyError:
  2287. if param.default is not _empty:
  2288. val = param.default
  2289. elif param.kind is _VAR_POSITIONAL:
  2290. val = ()
  2291. elif param.kind is _VAR_KEYWORD:
  2292. val = {}
  2293. else:
  2294. # This BoundArguments was likely produced by
  2295. # Signature.bind_partial().
  2296. continue
  2297. new_arguments.append((name, val))
  2298. self.arguments = OrderedDict(new_arguments)
  2299. def __eq__(self, other):
  2300. if self is other:
  2301. return True
  2302. if not isinstance(other, BoundArguments):
  2303. return NotImplemented
  2304. return (self.signature == other.signature and
  2305. self.arguments == other.arguments)
  2306. def __setstate__(self, state):
  2307. self._signature = state['_signature']
  2308. self.arguments = state['arguments']
  2309. def __getstate__(self):
  2310. return {'_signature': self._signature, 'arguments': self.arguments}
  2311. def __repr__(self):
  2312. args = []
  2313. for arg, value in self.arguments.items():
  2314. args.append('{}={!r}'.format(arg, value))
  2315. return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
  2316. class Signature:
  2317. """A Signature object represents the overall signature of a function.
  2318. It stores a Parameter object for each parameter accepted by the
  2319. function, as well as information specific to the function itself.
  2320. A Signature object has the following public attributes and methods:
  2321. * parameters : OrderedDict
  2322. An ordered mapping of parameters' names to the corresponding
  2323. Parameter objects (keyword-only arguments are in the same order
  2324. as listed in `code.co_varnames`).
  2325. * return_annotation : object
  2326. The annotation for the return type of the function if specified.
  2327. If the function has no annotation for its return type, this
  2328. attribute is set to `Signature.empty`.
  2329. * bind(*args, **kwargs) -> BoundArguments
  2330. Creates a mapping from positional and keyword arguments to
  2331. parameters.
  2332. * bind_partial(*args, **kwargs) -> BoundArguments
  2333. Creates a partial mapping from positional and keyword arguments
  2334. to parameters (simulating 'functools.partial' behavior.)
  2335. """
  2336. __slots__ = ('_return_annotation', '_parameters')
  2337. _parameter_cls = Parameter
  2338. _bound_arguments_cls = BoundArguments
  2339. empty = _empty
  2340. def __init__(self, parameters=None, *, return_annotation=_empty,
  2341. __validate_parameters__=True):
  2342. """Constructs Signature from the given list of Parameter
  2343. objects and 'return_annotation'. All arguments are optional.
  2344. """
  2345. if parameters is None:
  2346. params = OrderedDict()
  2347. else:
  2348. if __validate_parameters__:
  2349. params = OrderedDict()
  2350. top_kind = _POSITIONAL_ONLY
  2351. kind_defaults = False
  2352. for idx, param in enumerate(parameters):
  2353. kind = param.kind
  2354. name = param.name
  2355. if kind < top_kind:
  2356. msg = (
  2357. 'wrong parameter order: {} parameter before {} '
  2358. 'parameter'
  2359. )
  2360. msg = msg.format(_get_paramkind_descr(top_kind),
  2361. _get_paramkind_descr(kind))
  2362. raise ValueError(msg)
  2363. elif kind > top_kind:
  2364. kind_defaults = False
  2365. top_kind = kind
  2366. if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
  2367. if param.default is _empty:
  2368. if kind_defaults:
  2369. # No default for this parameter, but the
  2370. # previous parameter of the same kind had
  2371. # a default
  2372. msg = 'non-default argument follows default ' \
  2373. 'argument'
  2374. raise ValueError(msg)
  2375. else:
  2376. # There is a default for this parameter.
  2377. kind_defaults = True
  2378. if name in params:
  2379. msg = 'duplicate parameter name: {!r}'.format(name)
  2380. raise ValueError(msg)
  2381. params[name] = param
  2382. else:
  2383. params = OrderedDict(((param.name, param)
  2384. for param in parameters))
  2385. self._parameters = types.MappingProxyType(params)
  2386. self._return_annotation = return_annotation
  2387. @classmethod
  2388. def from_function(cls, func):
  2389. """Constructs Signature for the given python function.
  2390. Deprecated since Python 3.5, use `Signature.from_callable()`.
  2391. """
  2392. warnings.warn("inspect.Signature.from_function() is deprecated since "
  2393. "Python 3.5, use Signature.from_callable()",
  2394. DeprecationWarning, stacklevel=2)
  2395. return _signature_from_function(cls, func)
  2396. @classmethod
  2397. def from_builtin(cls, func):
  2398. """Constructs Signature for the given builtin function.
  2399. Deprecated since Python 3.5, use `Signature.from_callable()`.
  2400. """
  2401. warnings.warn("inspect.Signature.from_builtin() is deprecated since "
  2402. "Python 3.5, use Signature.from_callable()",
  2403. DeprecationWarning, stacklevel=2)
  2404. return _signature_from_builtin(cls, func)
  2405. @classmethod
  2406. def from_callable(cls, obj, *, follow_wrapped=True):
  2407. """Constructs Signature for the given callable object."""
  2408. return _signature_from_callable(obj, sigcls=cls,
  2409. follow_wrapper_chains=follow_wrapped)
  2410. @property
  2411. def parameters(self):
  2412. return self._parameters
  2413. @property
  2414. def return_annotation(self):
  2415. return self._return_annotation
  2416. def replace(self, *, parameters=_void, return_annotation=_void):
  2417. """Creates a customized copy of the Signature.
  2418. Pass 'parameters' and/or 'return_annotation' arguments
  2419. to override them in the new copy.
  2420. """
  2421. if parameters is _void:
  2422. parameters = self.parameters.values()
  2423. if return_annotation is _void:
  2424. return_annotation = self._return_annotation
  2425. return type(self)(parameters,
  2426. return_annotation=return_annotation)
  2427. def _hash_basis(self):
  2428. params = tuple(param for param in self.parameters.values()
  2429. if param.kind != _KEYWORD_ONLY)
  2430. kwo_params = {param.name: param for param in self.parameters.values()
  2431. if param.kind == _KEYWORD_ONLY}
  2432. return params, kwo_params, self.return_annotation
  2433. def __hash__(self):
  2434. params, kwo_params, return_annotation = self._hash_basis()
  2435. kwo_params = frozenset(kwo_params.values())
  2436. return hash((params, kwo_params, return_annotation))
  2437. def __eq__(self, other):
  2438. if self is other:
  2439. return True
  2440. if not isinstance(other, Signature):
  2441. return NotImplemented
  2442. return self._hash_basis() == other._hash_basis()
  2443. def _bind(self, args, kwargs, *, partial=False):
  2444. """Private method. Don't use directly."""
  2445. arguments = OrderedDict()
  2446. parameters = iter(self.parameters.values())
  2447. parameters_ex = ()
  2448. arg_vals = iter(args)
  2449. while True:
  2450. # Let's iterate through the positional arguments and corresponding
  2451. # parameters
  2452. try:
  2453. arg_val = next(arg_vals)
  2454. except StopIteration:
  2455. # No more positional arguments
  2456. try:
  2457. param = next(parameters)
  2458. except StopIteration:
  2459. # No more parameters. That's it. Just need to check that
  2460. # we have no `kwargs` after this while loop
  2461. break
  2462. else:
  2463. if param.kind == _VAR_POSITIONAL:
  2464. # That's OK, just empty *args. Let's start parsing
  2465. # kwargs
  2466. break
  2467. elif param.name in kwargs:
  2468. if param.kind == _POSITIONAL_ONLY:
  2469. msg = '{arg!r} parameter is positional only, ' \
  2470. 'but was passed as a keyword'
  2471. msg = msg.format(arg=param.name)
  2472. raise TypeError(msg) from None
  2473. parameters_ex = (param,)
  2474. break
  2475. elif (param.kind == _VAR_KEYWORD or
  2476. param.default is not _empty):
  2477. # That's fine too - we have a default value for this
  2478. # parameter. So, lets start parsing `kwargs`, starting
  2479. # with the current parameter
  2480. parameters_ex = (param,)
  2481. break
  2482. else:
  2483. # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
  2484. # not in `kwargs`
  2485. if partial:
  2486. parameters_ex = (param,)
  2487. break
  2488. else:
  2489. msg = 'missing a required argument: {arg!r}'
  2490. msg = msg.format(arg=param.name)
  2491. raise TypeError(msg) from None
  2492. else:
  2493. # We have a positional argument to process
  2494. try:
  2495. param = next(parameters)
  2496. except StopIteration:
  2497. raise TypeError('too many positional arguments') from None
  2498. else:
  2499. if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
  2500. # Looks like we have no parameter for this positional
  2501. # argument
  2502. raise TypeError(
  2503. 'too many positional arguments') from None
  2504. if param.kind == _VAR_POSITIONAL:
  2505. # We have an '*args'-like argument, let's fill it with
  2506. # all positional arguments we have left and move on to
  2507. # the next phase
  2508. values = [arg_val]
  2509. values.extend(arg_vals)
  2510. arguments[param.name] = tuple(values)
  2511. break
  2512. if param.name in kwargs:
  2513. raise TypeError(
  2514. 'multiple values for argument {arg!r}'.format(
  2515. arg=param.name)) from None
  2516. arguments[param.name] = arg_val
  2517. # Now, we iterate through the remaining parameters to process
  2518. # keyword arguments
  2519. kwargs_param = None
  2520. for param in itertools.chain(parameters_ex, parameters):
  2521. if param.kind == _VAR_KEYWORD:
  2522. # Memorize that we have a '**kwargs'-like parameter
  2523. kwargs_param = param
  2524. continue
  2525. if param.kind == _VAR_POSITIONAL:
  2526. # Named arguments don't refer to '*args'-like parameters.
  2527. # We only arrive here if the positional arguments ended
  2528. # before reaching the last parameter before *args.
  2529. continue
  2530. param_name = param.name
  2531. try:
  2532. arg_val = kwargs.pop(param_name)
  2533. except KeyError:
  2534. # We have no value for this parameter. It's fine though,
  2535. # if it has a default value, or it is an '*args'-like
  2536. # parameter, left alone by the processing of positional
  2537. # arguments.
  2538. if (not partial and param.kind != _VAR_POSITIONAL and
  2539. param.default is _empty):
  2540. raise TypeError('missing a required argument: {arg!r}'. \
  2541. format(arg=param_name)) from None
  2542. else:
  2543. if param.kind == _POSITIONAL_ONLY:
  2544. # This should never happen in case of a properly built
  2545. # Signature object (but let's have this check here
  2546. # to ensure correct behaviour just in case)
  2547. raise TypeError('{arg!r} parameter is positional only, '
  2548. 'but was passed as a keyword'. \
  2549. format(arg=param.name))
  2550. arguments[param_name] = arg_val
  2551. if kwargs:
  2552. if kwargs_param is not None:
  2553. # Process our '**kwargs'-like parameter
  2554. arguments[kwargs_param.name] = kwargs
  2555. else:
  2556. raise TypeError(
  2557. 'got an unexpected keyword argument {arg!r}'.format(
  2558. arg=next(iter(kwargs))))
  2559. return self._bound_arguments_cls(self, arguments)
  2560. def bind(*args, **kwargs):
  2561. """Get a BoundArguments object, that maps the passed `args`
  2562. and `kwargs` to the function's signature. Raises `TypeError`
  2563. if the passed arguments can not be bound.
  2564. """
  2565. return args[0]._bind(args[1:], kwargs)
  2566. def bind_partial(*args, **kwargs):
  2567. """Get a BoundArguments object, that partially maps the
  2568. passed `args` and `kwargs` to the function's signature.
  2569. Raises `TypeError` if the passed arguments can not be bound.
  2570. """
  2571. return args[0]._bind(args[1:], kwargs, partial=True)
  2572. def __reduce__(self):
  2573. return (type(self),
  2574. (tuple(self._parameters.values()),),
  2575. {'_return_annotation': self._return_annotation})
  2576. def __setstate__(self, state):
  2577. self._return_annotation = state['_return_annotation']
  2578. def __repr__(self):
  2579. return '<{} {}>'.format(self.__class__.__name__, self)
  2580. def __str__(self):
  2581. result = []
  2582. render_pos_only_separator = False
  2583. render_kw_only_separator = True
  2584. for param in self.parameters.values():
  2585. formatted = str(param)
  2586. kind = param.kind
  2587. if kind == _POSITIONAL_ONLY:
  2588. render_pos_only_separator = True
  2589. elif render_pos_only_separator:
  2590. # It's not a positional-only parameter, and the flag
  2591. # is set to 'True' (there were pos-only params before.)
  2592. result.append('/')
  2593. render_pos_only_separator = False
  2594. if kind == _VAR_POSITIONAL:
  2595. # OK, we have an '*args'-like parameter, so we won't need
  2596. # a '*' to separate keyword-only arguments
  2597. render_kw_only_separator = False
  2598. elif kind == _KEYWORD_ONLY and render_kw_only_separator:
  2599. # We have a keyword-only parameter to render and we haven't
  2600. # rendered an '*args'-like parameter before, so add a '*'
  2601. # separator to the parameters list ("foo(arg1, *, arg2)" case)
  2602. result.append('*')
  2603. # This condition should be only triggered once, so
  2604. # reset the flag
  2605. render_kw_only_separator = False
  2606. result.append(formatted)
  2607. if render_pos_only_separator:
  2608. # There were only positional-only parameters, hence the
  2609. # flag was not reset to 'False'
  2610. result.append('/')
  2611. rendered = '({})'.format(', '.join(result))
  2612. if self.return_annotation is not _empty:
  2613. anno = formatannotation(self.return_annotation)
  2614. rendered += ' -> {}'.format(anno)
  2615. return rendered
  2616. def signature(obj, *, follow_wrapped=True):
  2617. """Get a signature object for the passed callable."""
  2618. return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
  2619. def _main():
  2620. """ Logic for inspecting an object given at command line """
  2621. import argparse
  2622. import importlib
  2623. parser = argparse.ArgumentParser()
  2624. parser.add_argument(
  2625. 'object',
  2626. help="The object to be analysed. "
  2627. "It supports the 'module:qualname' syntax")
  2628. parser.add_argument(
  2629. '-d', '--details', action='store_true',
  2630. help='Display info about the module rather than its source code')
  2631. args = parser.parse_args()
  2632. target = args.object
  2633. mod_name, has_attrs, attrs = target.partition(":")
  2634. try:
  2635. obj = module = importlib.import_module(mod_name)
  2636. except Exception as exc:
  2637. msg = "Failed to import {} ({}: {})".format(mod_name,
  2638. type(exc).__name__,
  2639. exc)
  2640. print(msg, file=sys.stderr)
  2641. sys.exit(2)
  2642. if has_attrs:
  2643. parts = attrs.split(".")
  2644. obj = module
  2645. for part in parts:
  2646. obj = getattr(obj, part)
  2647. if module.__name__ in sys.builtin_module_names:
  2648. print("Can't get info for builtin modules.", file=sys.stderr)
  2649. sys.exit(1)
  2650. if args.details:
  2651. print('Target: {}'.format(target))
  2652. print('Origin: {}'.format(getsourcefile(module)))
  2653. print('Cached: {}'.format(module.__cached__))
  2654. if obj is module:
  2655. print('Loader: {}'.format(repr(module.__loader__)))
  2656. if hasattr(module, '__path__'):
  2657. print('Submodule search path: {}'.format(module.__path__))
  2658. else:
  2659. try:
  2660. __, lineno = findsource(obj)
  2661. except Exception:
  2662. pass
  2663. else:
  2664. print('Line: {}'.format(lineno))
  2665. print('\n')
  2666. else:
  2667. print(getsource(obj))
  2668. if __name__ == "__main__":
  2669. _main()