Best Python code snippet using sure_python
forbiddenfruit.py
Source:forbiddenfruit.py
...22 ('ob_type', ctypes.POINTER(PyObject)),23]24class SlotsProxy(PyObject):25 _fields_ = [('dict', ctypes.POINTER(PyObject))]26def patchable_builtin(klass):27 # It's important to create variables here, we want those objects alive28 # within this whole scope.29 name = klass.__name__30 target = klass.__dict__31 # Hardcore introspection to find the `PyProxyDict` object that contains the32 # precious `dict` attribute.33 proxy_dict = SlotsProxy.from_address(id(target))34 namespace = {}35 # This is the way I found to `cast` this `proxy_dict.dict` into a python36 # object, cause the `from_address()` function returns the `py_object`37 # version38 ctypes.pythonapi.PyDict_SetItem(39 ctypes.py_object(namespace),40 ctypes.py_object(name),41 proxy_dict.dict,42 )43 return namespace[name]44@wraps(__builtin__.dir)45def __filtered_dir__(obj=None):46 name = hasattr(obj, '__name__') and obj.__name__ or obj.__class__.__name__47 if obj is None:48 # Return names from the local scope of the calling frame, taking into49 # account indirection added by __filtered_dir__50 calling_frame = inspect.currentframe().f_back51 return sorted(calling_frame.f_locals.keys())52 return sorted(set(__dir__(obj)).difference(__hidden_elements__[name]))53# Switching to the custom dir impl declared above54__hidden_elements__ = defaultdict(list)55__dir__ = dir56__builtin__.dir = __filtered_dir__57def curse(klass, attr, value, hide_from_dir=False):58 """Curse a built-in `klass` with `attr` set to `value`59 This function monkey-patches the built-in python object `attr` adding a new60 attribute to it. You can add any kind of argument to the `class`.61 It's possible to attach methods as class methods, just do the following:62 >>> def myclassmethod(cls):63 ... return cls(1.5)64 >>> curse(float, "myclassmethod", classmethod(myclassmethod))65 >>> float.myclassmethod()66 1.567 Methods will be automatically bound, so don't forget to add a self68 parameter to them, like this:69 >>> def hello(self):70 ... return self * 271 >>> curse(str, "hello", hello)72 >>> "yo".hello()73 "yoyo"74 """75 dikt = patchable_builtin(klass)76 old_value = dikt.get(attr, None)77 old_name = '_c_%s' % attr # do not use .format here, it breaks py2.{5,6}78 if old_value:79 dikt[old_name] = old_value80 if old_value:81 dikt[attr] = value82 try:83 dikt[attr].__name__ = old_value.__name__84 except (AttributeError, TypeError): # py2.5 will raise `TypeError`85 pass86 try:87 dikt[attr].__qualname__ = old_value.__qualname__88 except AttributeError:89 pass90 else:91 dikt[attr] = value92 if hide_from_dir:93 __hidden_elements__[klass.__name__].append(attr)94def reverse(klass, attr):95 """Reverse a curse in a built-in object96 This function removes *new* attributes. It's actually possible to remove97 any kind of attribute from any built-in class, but just DON'T DO IT :)98 Good:99 >>> curse(str, "blah", "bleh")100 >>> assert "blah" in dir(str)101 >>> reverse(str, "blah")102 >>> assert "blah" not in dir(str)103 Bad:104 >>> reverse(str, "strip")105 >>> " blah ".strip()106 Traceback (most recent call last):107 File "<stdin>", line 1, in <module>108 AttributeError: 'str' object has no attribute 'strip'109 """110 dikt = patchable_builtin(klass)111 del dikt[attr]112def curses(klass, name):113 """Decorator to add decorated method named `name` the class `klass`114 So you can use it like this:115 >>> @curses(dict, 'banner')116 ... def dict_banner(self):117 ... l = len(self)118 ... print('This dict has {0} element{1}'.format(119 ... l, l is 1 and '' or 's')120 >>> {'a': 1, 'b': 2}.banner()121 'This dict has 2 elements'122 """123 def wrapper(func):124 curse(klass, name, func)...
patch.py
Source:patch.py
...25 ('ob_type', ctypes.POINTER(PyObject)),26 ]27 class SlotsProxy(PyObject):28 _fields_ = [('dict', ctypes.POINTER(PyObject))]29 def patchable_builtin(klass):30 name = klass.__name__31 target = getattr(klass, '__dict__', name)32 if not isinstance(target, DictProxyType):33 return target34 proxy_dict = SlotsProxy.from_address(id(target))35 namespace = {}36 ctypes.pythonapi.PyDict_SetItem(37 ctypes.py_object(namespace),38 ctypes.py_object(name),39 proxy_dict.dict,40 )41 return namespace[name]42 try:43 import __builtin__ as builtins44 except ImportError:45 import builtins46 def make_prop(exp, is_none=False):47 return builtins.property(48 fget=lambda self: exp(self),49 fset=lambda self, other: None,50 fdel=lambda self, *args, **kwargs: None51 )52 from pyshould.expectation import Expectation, ExpectationNot, ExpectationAll, \53 ExpectationAny, ExpectationNone54 object_handler = patchable_builtin(object)55 object_handler['should'] = make_prop(Expectation)56 object_handler['should_not'] = make_prop(ExpectationNot)57 object_handler['should_all'] = make_prop(ExpectationAll)58 object_handler['should_any'] = make_prop(ExpectationAny)59 object_handler['should_none'] = make_prop(ExpectationNone)60 # None does not have a tp_dict associated to its PyObject, so this61 # is the only way we could make it work like we expected.62 none_handler = patchable_builtin(None.__class__)63 none_handler['should'] = Expectation(None)64 none_handler['should_not'] = ExpectationNot(None)65 none_handler['should_all'] = ExpectationAll(None)66 none_handler['should_any'] = ExpectationAny(None)67 none_handler['should_none'] = ExpectationNone(None)68else:69 from warnings import warn70 warn("pyshould's patch is only supported on cpython", DeprecationWarning)...
test_~str.py
Source:test_~str.py
...11__date__ = '2022-02-17 15:49:23'12from __future__ import print_function13import gc14import ctypes15def patchable_builtin(klass):16 refs = gc.get_referents(klass.__dict__)17 assert len(refs) == 118 return refs[0]19dikt = patchable_builtin(str)...
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!!