Skip to content

Instantly share code, notes, and snippets.

View python_properties.py
# both classes below implement Python properties using data descriptors
class StudentWithInlineProps:
def __init__(self, name="Default Name"):
self._name = name
# getting the values
def get_name(self):
print('Getting value')
return self._name
@ychennay
ychennay / foreign_key_deferred_attribute.py
Created Mar 21, 2020
ForeignKeyDeferredAttribute example
View foreign_key_deferred_attribute.py
class ForeignKeyDeferredAttribute(DeferredAttribute):
def __set__(self, instance, value):
if instance.__dict__.get(self.field.attname) != value and self.field.is_cached(instance):
self.field.delete_cached_value(instance)
instance.__dict__[self.field.attname] = value
View attribute_example.py
class NonNullStringDescriptor:
def __init__(self, value: str = "Default Name"):
self.value = value
def __get__(self, instance, owner):
print(f"__get__({self}, {instance}, {owner})")
return self.value
def __set__(self, instance, value):
@ychennay
ychennay / data_descriptor_c.c
Last active Mar 20, 2020
data descriptor logic in C
View data_descriptor_c.c
f = NULL;
if (descr != NULL) {
Py_INCREF(descr); // increase the reference count of the descriptor
f = descr->ob_type->tp_descr_get; // access the descriptor's getter method from the descriptor's PyTypeObject ob_type
if (f != NULL && PyDescr_IsData(descr)) {
res = f(descr, obj, (PyObject *)obj->ob_type); // actual call to the descriptor's __get__
if (res == NULL && suppress &&
PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear();
}
@ychennay
ychennay / person.py
Last active Mar 19, 2020
name mangling
View person.py
class Person:
def __init__(self, name):
self.__secret_attribute = 42
self.name = name
if __name__ == "__main__":
person = Person("Yu")
# print(person.__secret_attribute) # AttributeError: 'Person' object has no attribute '__secret_attribute'
@ychennay
ychennay / Student.java
Last active Mar 19, 2020
Example of Person class in Java
View Student.java
package com.yuchen;
public class Student {
public String name;
public float gpa;
public String getName() {
return name;
}
View inheritance.py
# Add fields from abstract base class if it wasn't overridden.
for field in parent_fields:
if (field.name not in field_names and
field.name not in new_class.__dict__ and
field.name not in inherited_attributes):
new_field = copy.deepcopy(field)
new_class.add_to_class(field.name, new_field)
# Replace parent links defined on this base by the new
# field. It will be appropriately resolved if required.
if field.one_to_one:
View proxy_val.py
# Basic setup for proxy models.
if is_proxy:
base = None
for parent in [kls for kls in parents if hasattr(kls, '_meta')]:
if parent._meta.abstract:
if parent._meta.fields:
raise TypeError(
"Abstract base class containing model fields not "
"permitted for proxy model '%s'." % name
)
View proxy_model.py
class Student(models.Model):
...
class SpecificStudent(Student):
class Meta:
proxy = True
def perform_student_specific_action(self):
# ...
pass
View private_fields.py
# Inherit private fields (like GenericForeignKey) from the parent
# class
for field in base._meta.private_fields:
if field.name in field_names:
if not base._meta.abstract:
raise FieldError(
'Local field %r in class %r clashes with field of '
'the same name from base class %r.' % (
field.name,
name,