inspect.py 124 KB

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