I'm trying to create object dynamically using type
. Specifically, I want to create a float which has a len
.
This is what I tried:
_float = type('_float', (float,), {})
Another file, where's the instance created using function (constructor) reference:
obj = x[1](x[0]) # `x` is a 2-length tuple: (value, function)
obj.old = x[0]
obj.__len__ = lambda: len(x[0]) # I'm not sure if this lambda should take argument 'self'
out.append(obj) # 'out' is a list of output
This code is in loop, and when it's done, I run following (for testing where's the bug):
print(out[0].old) # => 1, correct
print(out[0].__len__) # <function bla.bla.<lambda> at: 0xblabla>
print(out[0].__len__()) # 1, correct (number of digits)
print(len(out[0])) # TypeError: object of type '_float' has no len()
The basic idea is that the user imports my module, gives it a str
value and a function. My module's object then applies that function to the str
value and returns a resulting object. However, it must keep the original value or at least its __len__
.