Best Python code snippet using molecule_python
objectmodel.py
Source:objectmodel.py
1# Copyright (c) 2016-2018 Claudiu Popa <pcmanticore@gmail.com>2# Copyright (c) 2016 Derek Gustafson <degustaf@gmail.com>3# Copyright (c) 2017-2018 Bryce Guinta <bryce.paul.guinta@gmail.com>4# Copyright (c) 2017 Ceridwen <ceridwenv@gmail.com>5# Copyright (c) 2017 Calen Pennington <cale@edx.org>6# Copyright (c) 2018 Nick Drozd <nicholasdrozd@gmail.com>7# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html8# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER9"""10Data object model, as per https://docs.python.org/3/reference/datamodel.html.11This module describes, at least partially, a data object model for some12of astroid's nodes. The model contains special attributes that nodes such13as functions, classes, modules etc have, such as __doc__, __class__,14__module__ etc, being used when doing attribute lookups over nodes.15For instance, inferring `obj.__class__` will first trigger an inference16of the `obj` variable. If it was successfully inferred, then an attribute17`__class__ will be looked for in the inferred object. This is the part18where the data model occurs. The model is attached to those nodes19and the lookup mechanism will try to see if attributes such as20`__class__` are defined by the model or not. If they are defined,21the model will be requested to return the corresponding value of that22attribute. Thus the model can be viewed as a special part of the lookup23mechanism.24"""25import builtins26import itertools27import pprint28import os29import types30from functools import lru_cache31import astroid32from astroid import context as contextmod33from astroid import exceptions34from astroid import node_classes35def _dunder_dict(instance, attributes):36 obj = node_classes.Dict(parent=instance)37 # Convert the keys to node strings38 keys = [node_classes.Const(value=value, parent=obj)39 for value in list(attributes.keys())]40 # The original attribute has a list of elements for each key,41 # but that is not useful for retrieving the special attribute's value.42 # In this case, we're picking the last value from each list.43 values = [elem[-1] for elem in attributes.values()]44 obj.postinit(list(zip(keys, values)))45 return obj46class ObjectModel:47 def __init__(self):48 self._instance = None49 def __repr__(self):50 result = []51 cname = type(self).__name__52 string = '%(cname)s(%(fields)s)'53 alignment = len(cname) + 154 for field in sorted(self.attributes()):55 width = 80 - len(field) - alignment56 lines = pprint.pformat(field, indent=2,57 width=width).splitlines(True)58 inner = [lines[0]]59 for line in lines[1:]:60 inner.append(' ' * alignment + line)61 result.append(field)62 return string % {'cname': cname,63 'fields': (',\n' + ' ' * alignment).join(result)}64 def __call__(self, instance):65 self._instance = instance66 return self67 def __get__(self, instance, cls=None):68 # ObjectModel needs to be a descriptor so that just doing69 # `special_attributes = SomeObjectModel` should be enough in the body of a node.70 # But at the same time, node.special_attributes should return an object71 # which can be used for manipulating the special attributes. That's the reason72 # we pass the instance through which it got accessed to ObjectModel.__call__,73 # returning itself afterwards, so we can still have access to the74 # underlying data model and to the instance for which it got accessed.75 return self(instance)76 def __contains__(self, name):77 return name in self.attributes()78 @lru_cache(maxsize=None)79 def attributes(self):80 """Get the attributes which are exported by this object model."""81 return [obj[2:] for obj in dir(self) if obj.startswith('py')]82 def lookup(self, name):83 """Look up the given *name* in the current model84 It should return an AST or an interpreter object,85 but if the name is not found, then an AttributeInferenceError will be raised.86 """87 if name in self.attributes():88 return getattr(self, "py" + name)89 raise exceptions.AttributeInferenceError(target=self._instance, attribute=name)90class ModuleModel(ObjectModel):91 def _builtins(self):92 builtins_ast_module = astroid.MANAGER.astroid_cache[builtins.__name__]93 return builtins_ast_module.special_attributes.lookup('__dict__')94 @property95 def pybuiltins(self):96 return self._builtins()97 # __path__ is a standard attribute on *packages* not98 # non-package modules. The only mention of it in the99 # official 2.7 documentation I can find is in the100 # tutorial.101 @property102 def py__path__(self):103 if not self._instance.package:104 raise exceptions.AttributeInferenceError(target=self._instance,105 attribute='__path__')106 path_objs = [107 node_classes.Const(108 value=path if not path.endswith('__init__.py') else os.path.dirname(path),109 parent=self._instance110 )111 for path in self._instance.path112 ]113 container = node_classes.List(parent=self._instance)114 container.postinit(path_objs)115 return container116 @property117 def py__name__(self):118 return node_classes.Const(value=self._instance.name,119 parent=self._instance)120 @property121 def py__doc__(self):122 return node_classes.Const(value=self._instance.doc,123 parent=self._instance)124 @property125 def py__file__(self):126 return node_classes.Const(value=self._instance.file,127 parent=self._instance)128 @property129 def py__dict__(self):130 return _dunder_dict(self._instance, self._instance.globals)131 # __package__ isn't mentioned anywhere outside a PEP:132 # https://www.python.org/dev/peps/pep-0366/133 @property134 def py__package__(self):135 if not self._instance.package:136 value = ''137 else:138 value = self._instance.name139 return node_classes.Const(value=value, parent=self._instance)140 # These are related to the Python 3 implementation of the141 # import system,142 # https://docs.python.org/3/reference/import.html#import-related-module-attributes143 @property144 def py__spec__(self):145 # No handling for now.146 return node_classes.Unknown()147 @property148 def py__loader__(self):149 # No handling for now.150 return node_classes.Unknown()151 @property152 def py__cached__(self):153 # No handling for now.154 return node_classes.Unknown()155class FunctionModel(ObjectModel):156 @property157 def py__name__(self):158 return node_classes.Const(value=self._instance.name,159 parent=self._instance)160 @property161 def py__doc__(self):162 return node_classes.Const(value=self._instance.doc,163 parent=self._instance)164 @property165 def py__qualname__(self):166 return node_classes.Const(value=self._instance.qname(),167 parent=self._instance)168 @property169 def py__defaults__(self):170 func = self._instance171 if not func.args.defaults:172 return node_classes.Const(value=None, parent=func)173 defaults_obj = node_classes.Tuple(parent=func)174 defaults_obj.postinit(func.args.defaults)175 return defaults_obj176 @property177 def py__annotations__(self):178 obj = node_classes.Dict(parent=self._instance)179 if not self._instance.returns:180 returns = None181 else:182 returns = self._instance.returns183 args = self._instance.args184 pair_annotations = itertools.chain(185 zip(args.args or [], args.annotations),186 zip(args.kwonlyargs, args.kwonlyargs_annotations)187 )188 annotations = {189 arg.name: annotation190 for (arg, annotation) in pair_annotations191 if annotation192 }193 if args.varargannotation:194 annotations[args.vararg] = args.varargannotation195 if args.kwargannotation:196 annotations[args.kwarg] = args.kwargannotation197 if returns:198 annotations['return'] = returns199 items = [(node_classes.Const(key, parent=obj), value)200 for (key, value) in annotations.items()]201 obj.postinit(items)202 return obj203 @property204 def py__dict__(self):205 return node_classes.Dict(parent=self._instance)206 py__globals__ = py__dict__207 @property208 def py__kwdefaults__(self):209 def _default_args(args, parent):210 for arg in args.kwonlyargs:211 try:212 default = args.default_value(arg.name)213 except exceptions.NoDefault:214 continue215 name = node_classes.Const(arg.name, parent=parent)216 yield name, default217 args = self._instance.args218 obj = node_classes.Dict(parent=self._instance)219 defaults = dict(_default_args(args, obj))220 obj.postinit(list(defaults.items()))221 return obj222 @property223 def py__module__(self):224 return node_classes.Const(self._instance.root().qname())225 @property226 def py__get__(self):227 from astroid import bases228 func = self._instance229 class DescriptorBoundMethod(bases.BoundMethod):230 """Bound method which knows how to understand calling descriptor binding."""231 def implicit_parameters(self):232 # Different than BoundMethod since the signature233 # is different.234 return 0235 def infer_call_result(self, caller, context=None):236 if len(caller.args) != 2:237 raise exceptions.InferenceError(238 "Invalid arguments for descriptor binding",239 target=self, context=context)240 context = contextmod.copy_context(context)241 cls = next(caller.args[0].infer(context=context))242 if cls is astroid.Uninferable:243 raise exceptions.InferenceError(244 "Invalid class inferred",245 target=self, context=context)246 # For some reason func is a Node that the below247 # code is not expecting248 if isinstance(func, bases.BoundMethod):249 yield func250 return251 # Rebuild the original value, but with the parent set as the252 # class where it will be bound.253 new_func = func.__class__(name=func.name, doc=func.doc,254 lineno=func.lineno, col_offset=func.col_offset,255 parent=cls)256 # pylint: disable=no-member257 new_func.postinit(func.args, func.body,258 func.decorators, func.returns)259 # Build a proper bound method that points to our newly built function.260 proxy = bases.UnboundMethod(new_func)261 yield bases.BoundMethod(proxy=proxy, bound=cls)262 @property263 def args(self):264 """Overwrite the underlying args to match those of the underlying func265 Usually the underlying *func* is a function/method, as in:266 def test(self):267 pass268 This has only the *self* parameter but when we access test.__get__269 we get a new object which has two parameters, *self* and *type*.270 """271 nonlocal func272 params = func.args.args.copy()273 params.append(astroid.AssignName(name='type'))274 arguments = astroid.Arguments(parent=func.args.parent,)275 arguments.postinit(276 args=params,277 defaults=[],278 kwonlyargs=[],279 kw_defaults=[],280 annotations=[],281 )282 return arguments283 return DescriptorBoundMethod(proxy=self._instance, bound=self._instance)284 # These are here just for completion.285 @property286 def py__ne__(self):287 return node_classes.Unknown()288 py__subclasshook__ = py__ne__289 py__str__ = py__ne__290 py__sizeof__ = py__ne__291 py__setattr__ = py__ne__292 py__repr__ = py__ne__293 py__reduce__ = py__ne__294 py__reduce_ex__ = py__ne__295 py__new__ = py__ne__296 py__lt__ = py__ne__297 py__eq__ = py__ne__298 py__gt__ = py__ne__299 py__format__ = py__ne__300 py__delattr__ = py__ne__301 py__getattribute__ = py__ne__302 py__hash__ = py__ne__303 py__init__ = py__ne__304 py__dir__ = py__ne__305 py__call__ = py__ne__306 py__class__ = py__ne__307 py__closure__ = py__ne__308 py__code__ = py__ne__309class ClassModel(ObjectModel):310 @property311 def py__module__(self):312 return node_classes.Const(self._instance.root().qname())313 @property314 def py__name__(self):315 return node_classes.Const(self._instance.name)316 @property317 def py__qualname__(self):318 return node_classes.Const(self._instance.qname())319 @property320 def py__doc__(self):321 return node_classes.Const(self._instance.doc)322 @property323 def py__mro__(self):324 if not self._instance.newstyle:325 raise exceptions.AttributeInferenceError(target=self._instance,326 attribute='__mro__')327 mro = self._instance.mro()328 obj = node_classes.Tuple(parent=self._instance)329 obj.postinit(mro)330 return obj331 @property332 def pymro(self):333 if not self._instance.newstyle:334 raise exceptions.AttributeInferenceError(target=self._instance,335 attribute='mro')336 from astroid import bases337 other_self = self338 # Cls.mro is a method and we need to return one in order to have a proper inference.339 # The method we're returning is capable of inferring the underlying MRO though.340 class MroBoundMethod(bases.BoundMethod):341 def infer_call_result(self, caller, context=None):342 yield other_self.py__mro__343 implicit_metaclass = self._instance.implicit_metaclass()344 mro_method = implicit_metaclass.locals['mro'][0]345 return MroBoundMethod(proxy=mro_method, bound=implicit_metaclass)346 @property347 def py__bases__(self):348 obj = node_classes.Tuple()349 context = contextmod.InferenceContext()350 elts = list(self._instance._inferred_bases(context))351 obj.postinit(elts=elts)352 return obj353 @property354 def py__class__(self):355 from astroid import helpers356 return helpers.object_type(self._instance)357 @property358 def py__subclasses__(self):359 """Get the subclasses of the underlying class360 This looks only in the current module for retrieving the subclasses,361 thus it might miss a couple of them.362 """363 from astroid import bases364 from astroid import scoped_nodes365 if not self._instance.newstyle:366 raise exceptions.AttributeInferenceError(target=self._instance,367 attribute='__subclasses__')368 qname = self._instance.qname()369 root = self._instance.root()370 classes = [cls for cls in root.nodes_of_class(scoped_nodes.ClassDef)371 if cls != self._instance and cls.is_subtype_of(qname)]372 obj = node_classes.List(parent=self._instance)373 obj.postinit(classes)374 class SubclassesBoundMethod(bases.BoundMethod):375 def infer_call_result(self, caller, context=None):376 yield obj377 implicit_metaclass = self._instance.implicit_metaclass()378 subclasses_method = implicit_metaclass.locals['__subclasses__'][0]379 return SubclassesBoundMethod(proxy=subclasses_method,380 bound=implicit_metaclass)381 @property382 def py__dict__(self):383 return node_classes.Dict(parent=self._instance)384class SuperModel(ObjectModel):385 @property386 def py__thisclass__(self):387 return self._instance.mro_pointer388 @property389 def py__self_class__(self):390 return self._instance._self_class391 @property392 def py__self__(self):393 return self._instance.type394 @property395 def py__class__(self):396 return self._instance._proxied397class UnboundMethodModel(ObjectModel):398 @property399 def py__class__(self):400 from astroid import helpers401 return helpers.object_type(self._instance)402 @property403 def py__func__(self):404 return self._instance._proxied405 @property406 def py__self__(self):407 return node_classes.Const(value=None, parent=self._instance)408 pyim_func = py__func__409 pyim_class = py__class__410 pyim_self = py__self__411class BoundMethodModel(FunctionModel):412 @property413 def py__func__(self):414 return self._instance._proxied._proxied415 @property416 def py__self__(self):417 return self._instance.bound418class GeneratorModel(FunctionModel):419 def __new__(cls, *args, **kwargs):420 # Append the values from the GeneratorType unto this object.421 ret = super(GeneratorModel, cls).__new__(cls, *args, **kwargs)422 generator = astroid.MANAGER.astroid_cache[builtins.__name__]['generator']423 for name, values in generator.locals.items():424 method = values[0]425 patched = lambda cls, meth=method: meth426 setattr(type(ret), 'py' + name, property(patched))427 return ret428 @property429 def py__name__(self):430 return node_classes.Const(value=self._instance.parent.name,431 parent=self._instance)432 @property433 def py__doc__(self):434 return node_classes.Const(value=self._instance.parent.doc,435 parent=self._instance)436class InstanceModel(ObjectModel):437 @property438 def py__class__(self):439 return self._instance._proxied440 @property441 def py__module__(self):442 return node_classes.Const(self._instance.root().qname())443 @property444 def py__doc__(self):445 return node_classes.Const(self._instance.doc)446 @property447 def py__dict__(self):448 return _dunder_dict(self._instance, self._instance.instance_attrs)449class ExceptionInstanceModel(InstanceModel):450 @property451 def pyargs(self):452 message = node_classes.Const('')453 args = node_classes.Tuple(parent=self._instance)454 args.postinit((message, ))455 return args456 @property457 def py__traceback__(self):458 builtins_ast_module = astroid.MANAGER.astroid_cache[builtins.__name__]459 traceback_type = builtins_ast_module[types.TracebackType.__name__]460 return traceback_type.instantiate_class()461class DictModel(ObjectModel):462 @property463 def py__class__(self):464 return self._instance._proxied465 def _generic_dict_attribute(self, obj, name):466 """Generate a bound method that can infer the given *obj*."""467 class DictMethodBoundMethod(astroid.BoundMethod):468 def infer_call_result(self, caller, context=None):469 yield obj470 meth = next(self._instance._proxied.igetattr(name))471 return DictMethodBoundMethod(proxy=meth, bound=self._instance)472 @property473 def pyitems(self):474 elems = []475 obj = node_classes.List(parent=self._instance)476 for key, value in self._instance.items:477 elem = node_classes.Tuple(parent=obj)478 elem.postinit((key, value))479 elems.append(elem)480 obj.postinit(elts=elems)481 from astroid import objects482 obj = objects.DictItems(obj)483 return self._generic_dict_attribute(obj, 'items')484 @property485 def pykeys(self):486 keys = [key for (key, _) in self._instance.items]487 obj = node_classes.List(parent=self._instance)488 obj.postinit(elts=keys)489 from astroid import objects490 obj = objects.DictKeys(obj)491 return self._generic_dict_attribute(obj, 'keys')492 @property493 def pyvalues(self):494 values = [value for (_, value) in self._instance.items]495 obj = node_classes.List(parent=self._instance)496 obj.postinit(values)497 from astroid import objects498 obj = objects.DictValues(obj)...
libedax_class.py
Source:libedax_class.py
...31 32 self.temp_dylib_path = self.__class__.temp_dir_path / f"libedax_{id(self)}.so"33 shutil.copy(dylib_path, self.temp_dylib_path)34 self._instance = cdll.LoadLibrary(self.temp_dylib_path)35 self.initialize_instance()36 37 self.edax_args = [38 "",39 "-book-file",40 str(book_file_path),41 "-eval-file",42 str(eval_file_path),43 "-level",44 str(level)45 ]46 47 self.libedax_initialize(48 len(self.edax_args),49 to_cstr_array(self.edax_args)50 )51 self.edax_init()52 def terminate(self):53 self.libedax_terminate()54 self.ui_free_libedax()55 def __dell__(self):56 self.terminate()57 58 # å±æ§ãå®ç¾©ããã¦ããªããã°, edaxã®å
±æã©ã¤ãã©ãªã®ã¤ã³ã¹ã¿ã³ã¹ãå¼ã³åºã59 def __getattr__(self, name):60 return getattr(self._instance, name)61 def initialize_instance(self):62 self._instance.libedax_initialize.restype = None;63 self._instance.libedax_initialize.argtypes = [c_int, POINTER(c_char_p)];64 self._instance.libedax_terminate.restype = None;65 self._instance.libedax_terminate.argtypes = [];66 self._instance.edax_init.restype = None;67 self._instance.edax_init.argtypes = [];68 self._instance.edax_new.restype = None;69 self._instance.edax_new.argtypes = [];70 self._instance.edax_load.restype = None;71 self._instance.edax_load.argtypes = [c_char_p];72 self._instance.edax_save.restype = None;73 self._instance.edax_save.argtypes = [c_char_p];74 self._instance.edax_undo.restype = None;75 self._instance.edax_undo.argtypes = [];...
dicts.py
Source:dicts.py
1import codecs, os, json, re2from nltk.corpus import words3from nltk.stem import WordNetLemmatizer4from nltk.corpus import cmudict as cmud5from .uk_american import UKAmerican6class DictsSingleton():7 """8 Contains main reference data for looking up tokens9 Sets some ad-hoc entries10 Singleton11 """12 13 _instance = None14 def __new__(cls):15 if cls._instance is None:16 cls._instance = super().__new__(cls)17 cls._instance.words = words.words()18 cls._instance.lemmatizer = WordNetLemmatizer()19 cls._instance.cmudict = cmud.dict()20 cls._instance.uk_us_dict = UKAmerican().uk_us_dict21 cls._instance.cmudict["us"] = [['AH1', 'S']]22 cls._instance.cmudict["heaven"] = [['HH', 'EH1', 'V', 'AH0', 'N'], ['HH', 'EH1', 'N']]23 cls._instance.cmudict["heavens"] = [['HH', 'EH1', 'V', 'AH0', 'N', 'Z'], ['HH', 'EH1', 'N', 'Z']]24 cls._instance.cmudict["heavenly"] = [['HH', 'EH1', 'V', 'AH0', 'N', 'L', 'IY0'], ['HH', 'EH1', 'N', 'L', 'IY0']]25 cls._instance.cmudict["choir"] = [['K', 'W', 'AY1', 'ER0'], ['K', 'W', 'AY1', 'R']]26 cls._instance.cmudict["choirs"] = [['K', 'W', 'AY1', 'ER0', 'Z'], ['K', 'W', 'AY1', 'R', 'Z']]27 cls._instance.cmudict["forsooth"] = [[ 'F', 'ER0', 'S', 'OW1', 'TH']]28 cls._instance.cmudict["moon"] = [['M', 'UW1', 'N']]29 cls._instance.cmudict["dryad"] = [['D', 'R', "AY1", "AE0", "D"]]30 cls._instance.cmudict["dryads"] = [['D', 'R', "AY1", "AE0", "D", "Z"]]31 cls._instance.cmudict["bene"] = [['B', 'EH1', 'N', 'AH0'], ['B', 'EH1', 'N']]32 cls._instance.cmudict["wherefore"] = [["W", "EH1", "R", "F", "ER0"]]33 cls._instance.cmudict["thereon"] = [["DH", "EH0", "R", "AH1", "N"]]34 cls._instance.cmudict["whereon"] = [["W", "EH0", "R", "AH1", "N"]]35 f = os.path.join(os.path.dirname(__file__), 'files/emspelling.json')36 with codecs.open(f, 'r', encoding='utf-8') as f:37 temp = f.read()38 g = os.path.join(os.path.dirname(__file__), 'files/decruft.json')39 with codecs.open(g, 'r', encoding='utf-8') as f:40 dec = f.read()41 decruft = json.loads(dec)42 cls._instance.regularize_dicts = {43 "decruftre_macron": {re.compile(k): v for k,v in decruft.items()},44 "decruftre": {re.compile(k): v for k,v in decruft.items() if "~" not in k},45 "dictionary": json.loads(temp)46 }47 ...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!