we can solve this by taking advantage of python' weakref module this module provides weakvaluedictionary objectwhich basically allows us to store items in dictionary without the garbage collector caring about them if value is in weak referenced dictionary and there are no other references to that object stored anywhere in the application (that iswe sold out of lx models)the garbage collector will eventually clean up for us let' build the factory for our car flyweights firstimport weakref class carmodel_models weakref weakvaluedictionary(def __new__(clsmodel_name*args**kwargs)model cls _models get(model_nameif not modelmodel super(__new__(clscls _models[model_namemodel return model basicallywhenever we construct new flyweight with given namewe first look up that name in the weak referenced dictionaryif it existswe return that modelif notwe create new one either waywe know the __init__ method on the flyweight will be called every timeregardless of whether it is new or existing object our __init__ method can therefore look like thisdef __init__(selfmodel_nameair=falsetilt=falsecruise_control=falsepower_locks=falsealloy_wheels=falseusb_charger=false)if not hasattr(self"initted")self model_name model_name self air air self tilt tilt self cruise_control cruise_control self power_locks power_locks self alloy_wheels alloy_wheels self usb_charger usb_charger self initted=true the if statement ensures that we only initialize the object the first time __init__ is called this means we can call the factory later with just the model name and get the same flyweight object back howeverbecause the flyweight will be garbagecollected if no external references to it existwe have to be careful not to accidentally create new flyweight with null values