Cannonical way to do circular dependency in Nim - nim-lang

Suppose we have two modules: one defines an Object and one defines an ObjectFactory. The Object needs to have access to the ObjectFactory use some of its functions, and the ObjectFactory needs access the Object to be able to instantiate Objects.
What is the cannonical way to solve this in Nim if the Object is implemented in a module and the ObjectFactory is implemented in another module?

I am assuming that the issue here is with mutually recursive types, i.e. where the declarations of two or more types refer to one another. Methods or procedures that refer to one another are handled fine by mutually recursive imports, though one has to be careful with module initialization in this case.
As in most other languages that normally require mutually recursive types to be within the same module/compilation unit, there are two principal answers.
One solution is to have the two types within the same module that is imported by both the module that declares the object type and the module that declares the factory type (both types still need to be part of the same type clause). E.g., you create a separate file, called something like factory_types.nim, and put both types in it:
type
ObjectFactory = ref object
lastValue: Object
x: proc(): Object
Object = ref object
factory: ObjectFactory
This module would then be imported by both the module implementing the object and the module implementing the factory.
The other solution, where you can keep each type in its module, is parametric polymorphism, where a type parameter is used as a forward declaration. E.g., you do:
type
ObjectFactory[TargetType] = ref object
lastValue: TargetType
generator: proc(): TargetType
and elsewhere:
type
Object = ref object
factory: ObjectFactory[Object]

Related

Saving Object State with Pickle (objects containing objects)

I'm trying to figure out how to serialize an object with Pickle to a save file. My example is an object called World and this object has a list (named objects) of potentially hundreds of instantiated objects of different class types.
The problem is that Pickle won't let me serialize the items within the World.objects list because they aren't instantiated as attributes of World.
When I attempt to serialize with:
with open('gsave.pkl', 'wb') as output:
pickle.dump(world.objects, output, pickle.DEFAULT_PROTOCOL)
I get the following error:
_pickle.PicklingError: Can't pickle <class 'world.LargeHealthPotion'>:
attribute lookup LargeHealthPotion on world failed
So, my question is: what is an alternative way of storing the world.objects list items so that they are attributes of world rather than list items that don't get saved?
UPDATE
I think my issue isn't where the objects are stored; but rather that the class LargeHealthPotion (and many others) are dynamically created within the World class by operations such as this:
def __constructor__(self, n, cl, d, c, h, l):
# initialize super of class type
super(self.__class__, self).__init__(name=n, classtype=cl, description=d, cost=c,
hp=h, level=l)
# create the object class dynamically, utilizing __constructor__ for __init__ method
item = type(item_name,
(eval("{}.{}".format(name,row[1].value)),),
{'__init__':__constructor__})
# add new object to the global _objects object to be used throughout the world
self._objects[item_name] = item(obj_name, obj_classtype, obj_description, obj_cost,
obj_hp, obj_level)
When this finishes, I will have a new object like <world.LargeHealthPotion object at 0x103690ac8>. I do this dynamically because I don't want to explicitly have to create hundreds of different types of classes for each different type of object in my world. Instead, I create the class dynamically while iterating over the item name (with it's stats) that I want to create.
This introduces a problem though, because when pickling, it can't find the static reference to the class in order to deconstruct, or reconstruct the object...so it fails.
What else can I do? (Besides creating literal class references for each, and every, type of object I'm going to instantiate into my world.)
Pickle does not pickle classes, it instead relies on references to classes which doesn't work if the class was dynamically generated. (this answer has appropriate exert and bolding from documentation)
So pickle assumes that if your object is from the class called world.LargeHealthPotion then it check that that name actually resolves to the class that it will be able to use when unpickling, if it doesn't then you won't be able to reinitialize the object since it doesn't know how to reference the class. There are a few ways of getting around this:
Define __reduce__ to reconstruct object
I'm not sure how to demo this method to you, I'd need much more information about your setup to suggest how to implement this but I can describe it:
First you'd make a function or classmethod that could recreate one object based on the arguments (probably take class name, instance variables etc.) Then define __reduce__ on the object base class that would return that function along with the arguments needed to pass to it when unpickling.
Put the dynamic classes in the global scope
This is the quick and dirty solution. Assuming the class names do not conflict with other things defined in the world module you could theoretically insert the classes into the global scope by doing globals()[item_name] = item_type, but I do not recommend this as long term solution since it is very bad practice.
Don't use dynamic classes
This is definitely the way to go in my opinion, instead of using the type constructor, just define your own class named something like ObjectType that:
Is not a subclass of type so the instances would be pickle-able.
When an instance is it called constructs a new game-object that has a reference to the object type.
So assuming you have a class called GameObject that takes cls=<ObjectType object> you could setup the ObjectType class something like this:
class ObjectType:
def __init__(self, name, description):
self.item_name = name
self.base_item_description = description
#other qualities common to all objects of this type
def __call__(self, cost, level, hp):
#other qualities that are specific to each item
return GameObject(cls=self, cost=cost, level=level, hp=hp)
Here I am using the __call__ magic method so it uses the same notation as classes cls(params) to create instances, the cls=self would indicate to the (abstracted) GameObject constructor that the class (type) of GameObject is based on the ObjectType instance self. It doesn't have to be a keyword argument, but I'm not sure how else to make a coherent example code without knowing more about your program.

Interfacing and extending ApplicationClass

I am trying to write a module in F#, making it easier working with Excel, by extracting rows, columns, etc. along with type casting and so on. One of the first things I wanted to do, was to extend various classes/types to implement the IDisposable interface. I tried to write something like the following
type Excel.ApplicationClass with
interface IDisposable with
member this.Dispose() =
this.excel.Quit()
Marshal.ReleaseComObject(this.excel) |> ignore
What I wasn't aware of, was that I would get the following error "All implemented interfaces should be declared on the initial declaration of the type".
My question is the following: Since I am not allow to extend a type with an interface - what else could I do?
If you inherit from the base class it can work, like this
type myAppClass() =
inherit Excel.ApplicationClass() //may not be correct signature - you need to match the base constructor
interface IDisposable with
member this.Dispose() =
//function body

using dynamic with reflection

I've heared that the best practice to create an instance using reflection is by using a dynamic type variable.
What it means is that when we use the Activator.CreateInstance() method(that returns object) we assign it into a dynamic type instead of object type:
dynamic dog = Activator.CreateInstance("Zoo.Dog");
dog.Bark();
Instead of:
object dog = Activator.CreateInstance("Zoo.Dog");
Dog realDog = (Dog)dog;
realDog.Bark();
Is there any good reason to use dynamic other than the lack of casting?
If you have access to the type you are creating your instance from, then there is no need to use a dynamic type. You might need to use a dynamic type if you do not have access (in a static way) to the type, for instance when loading dynamically an assembly. If you use a dynamic type instead of a known type, each type you call a member of your instance that will use reflection under the hood. Besides, you won't have intellisense using dynamic types.
You can use the generic method CreateInstance<T> from the Activator class to create your instance.
Dog dog = Activator.CreateInstance<Dog>();
dog.Bark();
The dynamic keyword makes easier the interaction with dynamic languages (IronPython, IronRuby for instance) (Dynamic Language Runtime DLR) or COM Interop APIs, but it is not recommended (nor needed) to use it with known types.

Weird inheritance in Node.js

I've been poking into some Node.js modules in the hopes of learning something I could have missed while creating a module with similar functionality. Then I came across this code from Hound:
function Hound() {
//why this?
events.EventEmitter.call(this)
}
//ok, so inheriting the EventEmitter
util.inherits(Hound, events.EventEmitter);
I know that the util.inherits() function from Node.js creates a new Parent instance as the prototype of the child constructor as stated in the docs:
The prototype of constructor will be set to a new object created from superConstructor.
So if our constructor is inheriting EventEmitter through util.inherits(), what is that code in the constructor for?
It's just making your Hound class an EventEmitter object.
It gives your the EventEmitter instance methods to the class.
E.g., houndInstance.emit('something')
Other objects that are listening to these events can then respond to them.
Per your comment:
// constructor
function Hound() {
// equivalent of calling a "super" or "parent" constructor
SomeClass.call(this);
}
In JavaScript, .call(context) is a means of invoking a function in a specific context. In the example above, we're just calling the SomeClass constructor and passing this (the Hound class in this example) as the context.
From your comments:
But doesn't util.inherits() already cover that? Or am I missing something?
What you are missing is that util.inherits() merely inherits the parent object. It doesn't set up the constructor to automatically call the parent object's constructor. In most cases it would be enough since most objects don't do much initialization in their constructors.
But events.EventEmitter apparently does some initialization in the constructor that has some important side effects. Since prototypical inheritance does not automatically call the parent's constructor you need to call it manually in this case. Hence the events.EventEmitter.call(this) line.
Note that an alternative is to use the module pattern which always calls the parent's constructor. That is because the module pattern is not inheritance per-se but emulates inheritance by abusing the mixin/decorator pattern - it creates an object from the parent constructor and manually add attributes to it. Lots of people don't like the module pattern because it duplicates functions and attrubutes - hence they see it as wasting memory. Also, it's not proper inheritance and so breaks stuff like instanceof.

python: de-serializing objects

We have classes of this form classA version1, classA version2, classA version3 .. etc. This is same class that has been modified. Each "modification" creates a new version of a class. Each object has a version attribute which refers to the version of the class from which it was derived. eg ObjectA.version =1 # means it was derived from ClassA version1
Here is my problem. During object de-serializing, i would like to use the specific version of the class that was used to used to make the object. For example, if i am de-serializing object ObjectA with version=3 then ClassA version 3 should be used. Source code for all the different variations of the classes is stored.
This looks getting the object first the get the class. Any idea on how to approach this?
You have three options:
Custom serialisation/deserialisation - you can put version information and class information first.
Create a "union class" which has all of the members of all of the class versions, then use that to create an instance of the appropriate class.
Refactor to a common base class, and have each "version" inherit from that class.
I would recommend option 3, because then your versions can co-exist cleanly.

Resources