How to understand the difference between class_eval() and instance_eval()?

As the documentation says, class_eval evaluates the string or block in the context of the Module or Class. So the following pieces of code are equivalent: class String def lowercase self.downcase end end String.class_eval do def lowercase self.downcase end end In each case, the String class has been reopened and a new method defined. That … Read more

What’s an example use case for a Python classmethod?

Helper methods for initialization: class MyStream(object): @classmethod def from_file(cls, filepath, ignore_comments=False): with open(filepath, ‘r’) as fileobj: for obj in cls(fileobj, ignore_comments): yield obj @classmethod def from_socket(cls, socket, ignore_comments=False): raise NotImplemented # Placeholder until implemented def __init__(self, iterable, ignore_comments=False): …

__getattr__ for static/class variables

__getattr__() and __str__() for an object are found on its class, so if you want to customize those things for a class, you need the class-of-a-class. A metaclass. class FooType(type): def _foo_func(cls): return ‘foo!’ def _bar_func(cls): return ‘bar!’ def __getattr__(cls, key): if key == ‘Foo’: return cls._foo_func() elif key == ‘Bar’: return cls._bar_func() raise AttributeError(key) … Read more

wait for Element Upgrade in connectedCallback: FireFox and Chromium differences

I think the Chrome/Safari behaviour is less intuitive for the beginners, but with some more complex scenarios (for example with child custom elements) then it is much more consistant. See the different examples below. They act strangely in Firefox… Another use case that I don’t have the courage to code: when a document is parsed, … Read more

What is the difference between class method vs. class field function vs. class field arrow function?

There are differences between all 3 versions. This differences are in 3 areas: Who is this at runtime Where the function is assigned What is the type of this in typescript. Lets start with where they work just the same. Consider this class, with a class field: class Greeter { constructor(private x: string) { } … Read more

Attaching a decorator to all functions within a class

The cleanest way to do this, or to do other modifications to a class definition, is to define a metaclass. Alternatively, just apply your decorator at the end of the class definition using inspect: import inspect class Something: def foo(self): pass for name, fn in inspect.getmembers(Something, inspect.isfunction): setattr(Something, name, decorator(fn)) In practice of course you’ll … Read more