0

I have a module (some_module) with a file (somefile), containing an object I want to instantiate (foo).

from collections import namedtuple

foo = namedtuple('Foo', ['a', 'b'])

In certain situations I only know the path to this file so have been importing like so:

import importlib.util as iu

spec = iu.spec_from_file_location("some_module.somefile", 'path/to/some_module/somefile.py')
mod = iu.module_from_spec(spec)
spec.loader.exec_module(mod)

var1 = mod.foo(1 ,2)

This worked fine at first but in my unit testing I discovered that type(var) was not equal to the type of the original ie:

from some_module.somefile import foo

var2 = foo(1, 2)

print(type(var1) is type(var2))
print(isinstance(var1, var2.__class__)

Prints only False's, despite the fact that it appears that both var1 & var2 are functionally equivalent.

EDIT: I'm using python 3.9.5 and in my test code, the construction functions for var1 & var2 are in separate .py files, they get imported into a unit test which tries to check if both the objects are the same.

bidby
  • 708
  • 1
  • 10
  • 24
  • 1
    "both var1 & var2 are functionally equivalent" That doesn't make them *identical*. You've effectively told Python to run the same code twice, creating a new ``foo`` definition each time. – MisterMiyagi Jul 21 '21 at 14:57
  • I see, so type definitions look to the construction, and when it was run to define a type? I suppose the simplest solution is probably to extend my unit test to assert that they're functionally equivalent (comparing __ dir__ of both?) rather than asserting they're of the same type – bidby Jul 22 '21 at 06:34
  • 1
    "I see, so type definitions look to the construction, and when it was run to define a type?" In short, types are objects. Defining the same type twice gives you two separate types, just like instantiating the same object twice gives you two separate objects. – MisterMiyagi Jul 22 '21 at 08:45

0 Answers0