Skip to content

Instantly share code, notes, and snippets.

View ychennay's full-sized avatar

Yu Chen ychennay

View GitHub Profile
# 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 March 21, 2020 03:39
ForeignKeyDeferredAttribute example
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
@ychennay
ychennay / attribute_example.py
Last active March 21, 2020 02:25
attributes
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 March 20, 2020 01:20
data descriptor logic in 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 March 19, 2020 23:26
name mangling
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 March 19, 2020 22:57
Example of Person class in Java
package com.yuchen;
public class Student {
public String name;
public float gpa;
public String getName() {
return name;
}
@ychennay
ychennay / inheritance.py
Created March 18, 2020 06:56
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:
@ychennay
ychennay / proxy_val.py
Created March 18, 2020 06:49
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
)
@ychennay
ychennay / proxy_model.py
Created March 18, 2020 04:51
proxy_model.py
class Student(models.Model):
...
class SpecificStudent(Student):
class Meta:
proxy = True
def perform_student_specific_action(self):
# ...
pass
@ychennay
ychennay / private_fields.py
Created March 18, 2020 04:48
private fields
# 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,