inspect.py 121 KB

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