### Install Recordclass from PyPI Source: https://github.com/intellimath/recordclass/blob/main/examples/Readme.ipynb Instructions for installing the recordclass library using pip from the Python Package Index. ```bash pip install recordclass ``` -------------------------------- ### Install Recordclass from Directory Source: https://github.com/intellimath/recordclass/blob/main/examples/Readme.ipynb Instructions for installing the recordclass library locally from its source directory using setup.py. ```bash python setup.py install ``` -------------------------------- ### Example TableRow Instantiation (Commented Out) Source: https://github.com/intellimath/recordclass/blob/main/examples/csv_example2.ipynb Illustrates how to create instances of TableRow with different numbers of arguments and keyword arguments. This code is commented out and serves as an example of usage. ```python # outtable = OutputTable() # outtable.add(TableRow(1, 'Matt', 'obvious', '10.0.0.1')) # outtable.add(TableRow(2, 'Maria', 'obvious as usual', '10.1.0.1', 'some description', 'localnet', 'super_admin')) # outtable.add(TableRow(3, 'Maria', hostip='10.1.0.1', description='some description', source='localnet')) ``` -------------------------------- ### Install recordclass and run tests Source: https://github.com/intellimath/recordclass/blob/main/README.md Install the recordclass library in editable mode and run tests using pytest. ```bash pip3 install -e . pytest ``` -------------------------------- ### Run Recordclass Tests from Directory Source: https://github.com/intellimath/recordclass/blob/main/examples/Readme.ipynb Instructions for running the test suite for the recordclass library when installed from a local directory. ```bash python test_all.py ``` -------------------------------- ### Import Necessary Modules Source: https://github.com/intellimath/recordclass/blob/main/examples/what_is_recordclass.ipynb Import recordclass, dataobject, make_dataclass, sys, and collections.namedtuple for use in the examples. ```python from recordclass import recordclass, dataobject, make_dataclass from sys import getsizeof as sizeof from collections import namedtuple import sys print(sys.version) print(sys.platform) ``` -------------------------------- ### Run Recordclass Tests from PyPI Source: https://github.com/intellimath/recordclass/blob/main/examples/Readme.ipynb Instructions for running the test suite for the recordclass library after installation from PyPI, using a one-liner command. ```python python -c "from recordclass.test import *; test_all()" ``` -------------------------------- ### Data Structure Initialization Examples Source: https://github.com/intellimath/recordclass/blob/main/examples/what_is_recordclass.ipynb Demonstrates the initialization of various data structures including namedtuple, recordclass, a custom class with slots, a dictionary, tuple, list, and a dataobject created with `make_dataclass`. ```python STest = namedtuple("TEST", "a b c d e f g h i j k") nt = STest(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10,k=11) RTest = recordclass("RTEST", "a b c d e f g h i j k") rc = RTest(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10,k=11) class Test: __slots__ = ["a","b","c","d","e","f","g","h","i","j","k"] def __init__(self, a, b, c, d, e, f, g, h, i, j, k): self.a = a; self.b = b; self.c = c self.d = d; self.e = e; self.f = f self.g = g; self.h = h; self.i = i self.j = j; self.k = k b = Test(1,2,3,4,5,6,7,8,9,10,11) c = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10, 'k':11} d = (1,2,3,4,5,6,7,8,9,10,11) e = [1,2,3,4,5,6,7,8,9,10,11] f = (1,2,3,4,5,6,7,8,9,10,11) key = 10 DO = make_dataclass("DO", fields=("a","b","c","d","e","f","g","h","i","j","k"), sequence=True, fast_new=True) do = DO(1,2,3,4,5,6,7,8,9,10,11) ``` -------------------------------- ### Performance testing setup Source: https://github.com/intellimath/recordclass/blob/main/examples/performance_comparison.ipynb Initializes a dictionary to store performance statistics and defines a function to run tests for different object types. Imports the garbage collector for memory management during testing. ```python stats = {} def run_test(objType): import gc gc.collect() tstats = stats[objType] = {} print("====== %s Performance Report ======" % objType) print("Time it takes to create 'day' object is: ") TradeDay = eval("TradeDay%s" % objType) Prices = eval("Prices%s" % objType) data: Dict[str, TradeDay] = {} # data = sorteddict() obj_count = 100000 ``` -------------------------------- ### Define Point with @as_record adapter Source: https://github.com/intellimath/recordclass/blob/main/README.md Example of using the @as_record adapter for a Point dataclass. ```python @as_record() def Point(x:float, y:float, meta=None): pass ``` -------------------------------- ### Import and Print Python Version Source: https://github.com/intellimath/recordclass/blob/main/examples/Untitled1.ipynb Imports the dataobject from recordclass and prints the current Python version. This is a basic setup step. ```python from recordclass import dataobject from sys import version print(version) ``` -------------------------------- ### Display Python and recordclass versions Source: https://github.com/intellimath/recordclass/blob/main/examples/performance_cgc.ipynb Prints the current Python version and the installed recordclass version. ```python print(sys.version) print(__version__) ``` -------------------------------- ### Custom __new__ for Point dataobject Source: https://github.com/intellimath/recordclass/blob/main/README.md Example of defining a custom __new__ method for a Point dataobject. ```python class Point(dataobject): x:int y:int def __new__(cls, x=0, y=0): return dataobject.__new__(cls, x, y) ``` -------------------------------- ### Dataobject with Factory for default values Source: https://github.com/intellimath/recordclass/blob/main/README.md Example of using Factory to specify a factory function for default tuple values. ```python from recordclass import Factory class A(dataobject): x: tuple = Factory(lambda: (list(), dict())) a = A() b = A() assert a.x == ([],{{}}) assert id(a.x) != id(b.x) assert id(a.x[0]) != id(b.x[0]) assert id(a.x[1]) != id(b.x[1]) ``` -------------------------------- ### Representing Data Rows Source: https://github.com/intellimath/recordclass/blob/main/examples/csv_example2.ipynb This example demonstrates the structure of individual data rows, likely from a dataset. Each `Row` object contains named fields representing different data points. ```python Row(a1=119.8984375, a2=53.82550508, a3=0.143378486, a4=-0.528427658, a5=4.04180602, a6=24.57913147, a7=6.581293412, a8=44.89951492, a9=0.0) ``` ```python Row(a1=123.125, a2=50.33124651, a3=-0.087091427, a4=0.087932382, a5=1.280936455, a6=10.68864639, a7=14.63669101, a8=288.668932, a9=0.0) ``` ```python Row(a1=102.046875, a2=48.79050551, a3=0.45222638, a4=0.272447732, a5=2.37541806, a6=13.9284014, a7=9.127499454, a8=116.0232222, a9=0.0) ``` ```python Row(a1=119.4453125, a2=53.14305702, a3=0.012830273, a4=-0.378955989, a5=2.932274247, a6=17.9297569, a7=8.289888515, a8=81.34651657, a9=0.0) ``` ```python Row(a1=128.515625, a2=54.94585181, a3=-0.012552759, a4=-0.658278628, a5=2.891304348, a6=17.75294666, a7=8.913745414, a8=94.08210337, a9=0.0) ``` ```python Row(a1=128.15625, a2=46.89690113, a3=-0.179233074, a4=-0.005819915, a5=4.193979933, a6=22.25815766, a7=6.451755484, a8=46.48663173, a9=0.0) ``` ```python Row(a1=115.6171875, a2=40.29037592, a3=0.110702345, a4=0.513224267, a5=11.63963211, a6=39.95655753, a7=3.640288988, a8=12.68457562, a9=0.0) ``` ```python Row(a1=136.7421875, a2=44.39123754, a3=-0.22192524, a4=0.908084632, a5=2.105351171, a6=14.49837742, a7=10.13157115, a8=128.3951486, a9=0.0) ``` ```python Row(a1=135.265625, a2=48.14390609, a3=0.015920939, a4=-0.15877212, a5=8.539297659, a6=31.13487695, a7=4.082788387, a8=17.27267344, a9=0.0) ``` ```python Row(a1=113.9609375, a2=52.24736871, a3=0.127976811, a4=-0.457499415, a5=4.407190635, a6=26.29776588, a7=6.709564866, a8=47.4057088, a9=0.0) ``` ```python Row(a1=107.796875, a2=45.6803362, a3=0.655279783, a4=0.954879021, a5=1.7090301, a6=15.1907807, a7=11.52025038, a8=150.3053634, a9=0.0) ``` ```python Row(a1=124.5, a2=57.35361802, a3=-0.014849043, a4=-0.550963937, a5=4.783444816, a6=27.50164045, a7=6.090448645, a8=37.81809112, a9=0.0) ``` ```python Row(a1=119.296875, a2=46.45417086, a3=0.202629139, a4=0.12837064, a5=3.748327759, a6=18.8510099, a7=6.414682286, a8=50.85055687, a9=0.0) ``` ```python Row(a1=148.3828125, a2=51.200757, a3=-0.113195798, a4=-0.50223559, a5=1.408026756, a6=12.08791939, a7=12.5121354, a8=201.1278905, a9=0.0) ``` ```python Row(a1=109.4921875, a2=53.2901838, a3=0.2528458, a4=-0.319022964, a5=4.132943144, a6=25.89210734, a7=6.741542034, a8=46.83080307, a9=0.0) ``` ```python Row(a1=112.125, a2=46.30840906, a3=0.721646098, a4=0.612454163, a5=1.173076923, a6=11.04918969, a7=14.6307442, a8=273.2509626, a9=0.0) ``` ```python Row(a1=128.7734375, a2=45.80669555, a3=0.086169154, a4=-0.031764808, a5=2.66722408, a6=15.93295829, a7=8.75667197, a8=95.36727143, a9=0.0) ``` ```python Row(a1=140.265625, a2=48.93721813, a3=0.03252958, a4=0.119064502, a5=2.315217391, a6=19.87317992, a7=9.67260138, a8=98.89698457, a9=0.0) ``` ```python Row(a1=87.515625, a2=51.76343189, a3=1.070588903, a4=0.74283956, a5=15.67809365, a6=50.90591579, a7=3.141187931, a8=8.440045483, a9=0.0) ``` ```python Row(a1=132.140625, a2=42.09582342, a3=0.143191723, a4=0.876730035, a5=1.863712375, a6=13.26595667, a7=10.25798651, a8=140.0407088, a9=0.0) ``` ```python Row(a1=104.078125, a2=45.24078107, a3=0.532040422, a4=0.743853067, a5=1.43645485, a6=15.41478275, a7=11.89911604, a8=150.9872549, a9=0.0) ``` ```python Row(a1=122.6015625, a2=53.79697654, a3=-0.051964773, a4=-0.379729027, a5=2.636287625, a6=15.17095406, a7=9.519292364, a8=117.7422254, a9=0.0) ``` ```python Row(a1=114.28125, a2=41.25396525, a3=0.41182113, a4=0.616996141, a5=2.412207358, a6=20.42794216, a7=9.198391753, a8=88.37057957, a9=0.0) ``` ```python Row(a1=112.4375, a2=38.2956733, a3=0.501943444, a4=1.07484029, a5=2.81270903, a6=18.13688307, a7=7.859968426, a8=71.29944944, a9=0.0) ``` ```python Row(a1=23.625, a2=29.94865398, a3=5.688038235, a4=35.98717152, a5=146.5685619, a6=82.39462399, a7=-0.274901598, a8=-1.121848281, a9=1.0) ``` ```python Row(a1=94.5859375, a2=35.77982308, a3=1.187308683, a4=3.68746932, a5=6.071070234, a6=29.76039993, a7=5.318766827, a8=28.69804799, a9=1.0) ``` ```python Row(a1=137.2421875, a2=46.45474042, a3=0.045257133, a4=-0.438857507, a5=59.4958194, a6=77.75535652, a7=0.71974817, a8=-1.183162032, a9=0.0) ``` ```python Row(a1=123.53125, a2=53.34878418, a3=0.072077648, a4=-0.071600995, a5=0.781772575, a6=10.57083301, a7=17.11829958, a8=339.6608262, a9=0.0) ``` ```python Row(a1=70.0234375, a2=35.28067478, a3=1.157657193, a4=4.546692371, a5=3.003344482, a6=19.57538355, a7=7.954436097, a8=71.96015886, a9=0.0) ``` ```python Row(a1=129.375, a2=44.56841651, a3=0.049779493, a4=0.506330188, a5=3.60451505, a6=21.13303805, a7=7.181384025, a8=56.85662961, a9=0.0) ``` ```python Row(a1=97.140625, a2=47.77089438, a3=0.625218075, a4=0.740796144, a5=4.193143813, a6=26.46526062, a7=6.927045631, a8=49.62852693, a9=0.0) ``` ```python Row(a1=101.96875, a2=46.31632702, a3=0.439814307, a4=0.294261355, a5=1.748327759, a6=16.4866229, a7=10.8103928, a8=127.7333664, a9=0.0) ``` ```python Row(a1=123.46875, a2=45.47508547, a3=0.345780685, a4=0.647414924, a5=32.91973244, a6=65.09419657, a7=1.605538349, a8=0.871363737, a9=1.0) ``` ```python Row(a1=103.5234375, a2=45.72573893, a3=0.3365333, a4=0.520557925, a5=11.28929766, a6=39.11645317, a7=3.509139254, a8=11.50397981, a9=0.0) ``` ```python Row(a1=107.9296875, a2=50.58195448, a3=0.320398557, a4=0.277613139, a5=2.022575251, a6=19.80655592, a7=10.47225116, a8=113.0115374, a9=0.0) ``` -------------------------------- ### Get memory size of Dataobject instance Source: https://github.com/intellimath/recordclass/blob/main/README.md Get the memory size of a Point instance using sys.getsizeof(). ```python sys.getsizeof(p) ``` -------------------------------- ### Instantiate and Populate OutputTable Source: https://github.com/intellimath/recordclass/blob/main/examples/csv_example.ipynb Creates an instance of `OutputTable`, adds several `TableRow` records with varying levels of detail, and then exports the data to a CSV file named 'example.csv'. This demonstrates the practical usage of the `OutputTable` class. ```python outtable = OutputTable() outtable.add(TableRow(1, 'Matt', 'obvious', '10.0.0.1')) outtable.add(TableRow(2, 'Maria', 'obvious as usual', '10.1.0.1', 'some description', 'localnet', 'super_admin')) outtable.add(TableRow(3, 'Maria', hostip='10.1.0.1', description='some description', source='localnet')) outtable.to_csv('./example.csv') ``` -------------------------------- ### Instantiate and Initialize DataObject Source: https://github.com/intellimath/recordclass/blob/main/examples/issues/dataobject_pickle.ipynb Demonstrates creating an instance of Param using __new__ and then explicitly calling __init__ to set its attributes. ```python p = Param.__new__(Param, 1, 2) print(p) p.__init__(1, 2) print(p) ``` -------------------------------- ### Instantiate and print element Source: https://github.com/intellimath/recordclass/blob/main/examples/Untitled.ipynb Creates an instance of the element and prints it. ```python a = element('title', 'Titolo', 'it') print(a) ``` -------------------------------- ### Get Size of PointMS Instance Source: https://github.com/intellimath/recordclass/blob/main/examples/what_is_recordclass.ipynb Calculates and returns the memory size of a single PointMS instance. ```python sys.getsizeof(PointMS(1,2)) ``` -------------------------------- ### Get Size of PointRC Instance Source: https://github.com/intellimath/recordclass/blob/main/examples/what_is_recordclass.ipynb Calculates and returns the memory size of a single PointRC instance. ```python sys.getsizeof(PointRC(1,2)) ``` -------------------------------- ### Access Recordclass Fields Attribute Source: https://github.com/intellimath/recordclass/blob/main/examples/what_is_recordclass.ipynb Access the __fields__ attribute of a recordclass to get the names of its fields. ```python print(R.__fields__) ``` -------------------------------- ### Immutable dataobject class definition Source: https://github.com/intellimath/recordclass/blob/main/README.md Example of defining an immutable dataobject class using immutable_type=True. ```python immutable_type=True class Cls(dataobject): pass ``` -------------------------------- ### Prepare for second benchmark Source: https://github.com/intellimath/recordclass/blob/main/examples/tree_trigram.ipynb Initializes lists for storing data for a second benchmarking run, likely for the recordclass-based Ternary Search Tree. ```python gc.collect() ns2 = [] times2 = [] ``` -------------------------------- ### Memory Usage Utility Source: https://github.com/intellimath/recordclass/blob/main/examples/gc_less_classes.ipynb A utility function to get the current memory usage of the Python process in percentage. ```python import psutil import os import gc def memory_usage_psutil(): # return the memory usage in percentage like top process = psutil.Process(os.getpid()) mem = process.memory_percent() return mem ``` -------------------------------- ### Creating Instance with make Function Source: https://github.com/intellimath/recordclass/blob/main/README.md The 'make' function simplifies the creation of class instances by taking the class and its arguments, along with optional keyword arguments. ```python make(cls, args, **kwargs) ``` -------------------------------- ### Instantiate and print Point object Source: https://github.com/intellimath/recordclass/blob/main/README.md Demonstrates instantiation and printing of a Point object created with @as_record. ```python >>> p = Point(1,2) >>> print(p) Point(x=1, y=2, meta=None) ``` -------------------------------- ### Instantiate and Print DataObject Source: https://github.com/intellimath/recordclass/blob/main/examples/Untitled1.ipynb Creates an instance 'a' of the 'A' dataobject and prints it. Note that due to the custom __init__, the attributes are initialized to None. ```python a=A(1,2) print(a) ``` -------------------------------- ### Fast instance creation with fast_new option Source: https://github.com/intellimath/recordclass/blob/main/examples/dataobjects_by_exaample.ipynb The `fast_new=True` option can significantly speed up instance creation, especially for large numbers of instances. This is demonstrated by comparing the creation time of Point and FastPoint instances. ```python class FastPoint(dataobject, fast_new=True): x:int y:int ``` ```python %timeit l1 = [Point(i,i) for i in range(100000)] %timeit l2 = [FastPoint(i,i) for i in range(100000)] ``` -------------------------------- ### Import necessary libraries Source: https://github.com/intellimath/recordclass/blob/main/examples/performance_cgc.ipynb Imports recordclass, math, garbage collection, and system modules for benchmarking. ```python from recordclass import dataobject, __version__ from math import sqrt import gc import sys ``` -------------------------------- ### Get Keys from Fixed Dict-like Object Source: https://github.com/intellimath/recordclass/blob/main/examples/fixed_dictlike.ipynb Retrieves and prints a list of all keys from the MyFixedDict instance. This demonstrates the dictionary-like behavior of accessing keys. ```python print(list(d.keys())) ``` -------------------------------- ### Instantiate and set attributes using keyword arguments Source: https://github.com/intellimath/recordclass/blob/main/examples/issues/recordclass_kwargs.ipynb Creates an instance of 'Variant_Info' and sets its 'title' attribute. The `_make` method is used to initialize with a list of values, and then attributes can be set directly. ```python inst = _variant_info._make([None] * len(_items)) inst.title = 'Accountancy' ``` -------------------------------- ### Get Values from Fixed Dict-like Object Source: https://github.com/intellimath/recordclass/blob/main/examples/fixed_dictlike.ipynb Retrieves and prints a list of all values from the MyFixedDict instance. This showcases how to access all values stored within the object. ```python print(list(d.values())) ``` -------------------------------- ### Example Row Data Structure Source: https://github.com/intellimath/recordclass/blob/main/examples/csv_example2.ipynb This represents a sample Row object, likely from a recordclass, with various floating-point attributes. This data structure is what would be exported to CSV. ```python Row(a1=99.2890625, a2=47.39134816, a3=0.702001099, a4=1.042189754, a5=1.627090301, a6=14.68008008, a7=10.99141172, a8=139.5509004, a9=1.0) ``` -------------------------------- ### Instantiate and print recordclass C Source: https://github.com/intellimath/recordclass/blob/main/examples/issues/class_level_attrs.ipynb Creates an instance 'c' of recordclass 'C' with a single argument and prints it, showing the effect of its custom __init__. ```python c=C(1) print(c) ``` -------------------------------- ### Instantiate and Print Fixed Dict-like Object Source: https://github.com/intellimath/recordclass/blob/main/examples/fixed_dictlike.ipynb Creates an instance of MyFixedDict with initial values and prints its representation. The output shows the object with field names and their corresponding values. ```python d = MyFixedDict(1,2,3,4) ``` ```python print(d) ``` -------------------------------- ### Instantiate and print recordclass A Source: https://github.com/intellimath/recordclass/blob/main/examples/issues/class_level_attrs.ipynb Creates an instance 'a' of recordclass 'A' with a single argument and prints it. ```python a=A(1) print(a) ``` -------------------------------- ### Get current process RSS memory Source: https://github.com/intellimath/recordclass/blob/main/examples/psutil_memsize.ipynb Defines a function to retrieve the Resident Set Size (RSS) of the current Python process using psutil. This is useful for tracking memory consumption. ```python def get_memsize(): pid = os.getpid() ps = psutil.Process(pid) meminfo = ps.memory_info() return meminfo.rss ``` -------------------------------- ### Inheritance and Joining Classes with recordclass Source: https://github.com/intellimath/recordclass/blob/main/examples/recorclass_description.ipynb Demonstrates class inheritance and joining multiple classes using recordclass. Also shows attribute assignment and accessing instance dictionaries. ```python from recordclass import join_classes class B(A1): pass class C(B): pass D = join_classes('D', [A1, A2]) b=B(1,2,3) c=C(1,2,3) d=D(1,2,3,4,5,6) b.fff = 100 c.ggg = 200 ``` ```python b.__dict__, c.__dict__ ``` -------------------------------- ### Create DataObject Instance Directly Source: https://github.com/intellimath/recordclass/blob/main/examples/issues/dataobject_pickle.ipynb Shows the standard way to create an instance of the Param data object by passing arguments to the constructor. ```python p = Param(x=1, y=2) print(p) ``` -------------------------------- ### Non-iterable data object Source: https://github.com/intellimath/recordclass/blob/main/examples/dataobjects_by_exaample.ipynb By default, data object subclasses are iterable. To disable iterability, use the `iterable=False` argument during class definition. This example shows how attempting to iterate over a non-iterable PointNI instance raises a TypeError. ```python class PointNI(dataobject): x:int y:int ``` ```python try: [v for v in PointNI(1,2)] except TypeError as e: print(e) ``` -------------------------------- ### Instantiate and print recordclass B Source: https://github.com/intellimath/recordclass/blob/main/examples/issues/class_level_attrs.ipynb Creates an instance 'b' of recordclass 'B' with a single argument and prints it. ```python b=B(1) print(b) ``` -------------------------------- ### Instantiate and print a Point object Source: https://github.com/intellimath/recordclass/blob/main/examples/asrecord.ipynb Creates an instance of the Point record class with specified values for 'x' and 'y', and then prints the instance. The 'meta' field takes its default value. ```python p = Point(1,2) print(p) ``` -------------------------------- ### Data object with default values Source: https://github.com/intellimath/recordclass/blob/main/examples/dataobjects_by_exaample.ipynb Default values can be assigned to attributes. When creating an instance, attributes with default values can be omitted, and they will be set to their defaults. This example defines an RGB color object with default values for r, g, and b. ```python class RGB(dataobject): r:int = 0 g:int = 0 b:int = 0 ``` ```python p1 = RGB(128, 64) p2 = RGB(r=128, g=64) print(p1) print(p1 == p2) ``` -------------------------------- ### Invalid data object definition with default values Source: https://github.com/intellimath/recordclass/blob/main/examples/dataobjects_by_exaample.ipynb Fields without default values must appear before fields with default values. This example demonstrates the TypeError raised when a field without a default value follows a field with a default value. ```python try: class PointInvalidDefaults(dataobject): x:int = 0 y:int except TypeError as e: print(e) ``` -------------------------------- ### Creating and Printing recordclass Instances Source: https://github.com/intellimath/recordclass/blob/main/examples/recorclass_description.ipynb Shows how to create instances of recordclass with different attribute definitions and print them. ```python from recordclass import recordclass A1 = recordclass('A1', 'a, b, c') A2 = recordclass('A2', ['d', 'e', 'f']) a=A1(1,2,3) a3=A3(1,2,3) print(a) print(a3) ``` -------------------------------- ### Inspect DataObject Initialization Source: https://github.com/intellimath/recordclass/blob/main/examples/issues/dataobject_pickle.ipynb Prints information about the initialization methods and class hierarchy of the custom Param data object. ```python print(Param.__init__) print(Param.__new__) print(Param.__module__, Param.__name__, Param.__qualname__) print(type(Param)) print(Param.__base__.__base__) ``` -------------------------------- ### Create and Populate SQLite Table Source: https://github.com/intellimath/recordclass/blob/main/examples/sqlite_and_dataobject.ipynb This snippet demonstrates how to create a SQLite table and populate it with a large number of records using Python's `sqlite3` module and `executemany` for efficiency. ```python import sqlite3 from random import random, randint import sys N = 1000000 ``` ```python # !rm example.db # conn = sqlite3.connect('example.db') # c = conn.cursor() # c.execute('''CREATE TABLE test # (id int, x real, y real, p int, q int)''') # gen = ((i, random(), random(), randint(0,N), randint(0,N)) for i in range(N)) # c.executemany("INSERT INTO test VALUES (?,?,?,?,?)", gen) # conn.commit() # conn.close() ``` -------------------------------- ### Import make_dataclass and partial Source: https://github.com/intellimath/recordclass/blob/main/examples/Untitled.ipynb Imports make_dataclass from recordclass and partial from functools. ```python from recordclass import make_dataclass from functools import partial ``` -------------------------------- ### Fetch Data with `recordclass.make_dataclass` Source: https://github.com/intellimath/recordclass/blob/main/examples/sqlite_and_dataobject.ipynb Fetches data and instantiates `recordclass.make_dataclass` objects for each row, utilizing `fast_new=True` for potentially faster instantiation. Performance is measured and memory usage is estimated. ```python from recordclass import make_dataclass Row = make_dataclass("Row", "id x y p q", fast_new=True) conn = sqlite3.connect('example.db') c = conn.cursor() %time res = [Row(*row) for row in c.execute("SELECT id,x,y,p,q FROM test")] conn.close() print(N * sys.getsizeof(res[0]) // 1000000, 'Mb') del res ``` -------------------------------- ### Structclass Instance Attributes and Size Source: https://github.com/intellimath/recordclass/blob/main/examples/recorclass_description.ipynb Illustrates creating a structclass instance, checking for __dict__ and __weakref__, and printing its size. ```python import sys p = Point(1,2) try: p.__dict__ except AttributeError: print('*** There is no __dict__ ***') try: p.__weakref__ except AttributeError: print('*** There is no __weakref__ ***') print(p, 'sizeof:', sys.getsizeof(p)) ``` -------------------------------- ### Create and print Dataobject instance Source: https://github.com/intellimath/recordclass/blob/main/README.md Create an instance of the Point data class and print its default string representation. ```python p = Point(1, 2) print(p) ``` -------------------------------- ### Create and Compare Mutable and Immutable Tuples Source: https://github.com/intellimath/recordclass/blob/main/README.md Demonstrates the creation of mutabletuple and litetuple, and their comparison. Note that mutabletuple allows in-place modification, affecting subsequent comparisons. ```python import sys from recordclass import mutabletuple, litetuple lt = litetuple(1, 2, 3) mt = mutabletuple(1, 2, 3) print(lt == mt) mt[-1] = -3 print(lt == mt) print(sys.getsizeof((1,2,3)), sys.getsizeof(litetuple(1,2,3))) ``` -------------------------------- ### Performance comparison of data object creation Source: https://github.com/intellimath/recordclass/blob/main/examples/dataobjects_by_exaample.ipynb Compares the performance of creating instances using a custom `dataobject` with `fast_new=True` against a standard class with `__slots__`. This highlights the performance benefits of `fast_new` for intensive object creation. ```python class A(dataobject, fast_new=True): x:int y:int def __init__(self, x, y): if not (isinstance(x, int) and isinstance(y, int)): raise TypeError('x,y are not int') class B: __slots__ = 'x', 'y' x:int y:int def __init__(self, x, y): if not (isinstance(x, int) and isinstance(y, int)): raise TypeError('x,y are not int') self.x = x self.y = y ``` ```python %timeit l1 = [A(1,2) for i in range(1000000)] ``` ```python %timeit l2 = [B(1,2) for i in range(1000000)] ``` -------------------------------- ### Pickling and Copying Support for Fraction Source: https://github.com/intellimath/recordclass/blob/main/examples/fraction_dataobject.ipynb Provides methods for pickling, copying, and deep copying Fraction objects. Immutable instances return themselves for efficiency. ```python # support for pickling, copy, and deepcopy def __reduce__(self): return (self.__class__, (str(self),)) def __copy__(self): if type(self) == DFraction: return self # I'm immutable; therefore I am my own clone return self.__class__(self._numerator, self._denominator) def __deepcopy__(self, memo): if type(self) == DFraction: return self # My components are also immutable return self.__class__(self._numerator, self._denominator) ``` -------------------------------- ### Benchmark Point3 object creation Source: https://github.com/intellimath/recordclass/blob/main/examples/performance_cgc.ipynb Measures the time taken to create 1000 Point3 objects using %timeit. ```python gc.collect() %timeit test_point3(1000) ``` -------------------------------- ### Timing Tree Creation with Varying Sizes Source: https://github.com/intellimath/recordclass/blob/main/examples/tree_trigram.ipynb This snippet times the creation of tree structures using the 'train2' function for increasing sizes of 'n'. It records the time taken and prints the size and duration for each iteration. This is useful for benchmarking performance as data size grows. ```python times2_del = [] n = 1024 * 32 n2 = 1024 * 1024 * 2 while n < n2+1: t0 = time.time() tree2 = train2(n) del tree2 dt = time.time() - t0 ns2.append(n) times2.append(dt) print(n, "%.2f" % (dt,)) n = int(n * q2) ``` -------------------------------- ### Dataobject with default __match_args__ (Python 3.10+) Source: https://github.com/intellimath/recordclass/blob/main/README.md Define a User data class. For Python 3.10+, __match_args__ defaults to __fields__. ```python class User(dataobject): first_name: str last_name: str age: int __match_args__ = 'first_name', 'last_name' ``` -------------------------------- ### Timeit Benchmarks for Data Structures Source: https://github.com/intellimath/recordclass/blob/main/examples/stackoverflow_answer_1.ipynb Uses the %timeit magic command to benchmark the creation of dictionaries with different data structures. ```python %timeit d = {i: (i+1, 'hello', True) for i in range(1000000)} # tuple %timeit d = {i: {'id':i+1, 'name':'hello', 'isvalid':True} for i in range(1000000)} # dict %timeit d = {i: Tri(i+1, 'hello', True) for i in range(1000000)} # namedtuple %timeit d = {i: Tri2(i+1, 'hello', True) for i in range(1000000)} # NamedTuple %timeit d = {i: TriDO(i+1, 'hello', True) for i in range(1000000)} # dataobject ```