inspect.py 115 KB

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