inspect.py 123 KB

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