-2

I'm confused. How type() takes more than on parameter? And what is the core purpose on this expression?

self.data = [type('', (), dict(output=input))() for input in dnn_input_list]

Somebody help me to understand why code is written like this.

destructioneer
  • 150
  • 1
  • 10
Gold
  • 11
  • 2
  • `type` can be used to dynamically create classes. See this question for more details: https://stackoverflow.com/questions/15247075/how-can-i-dynamically-create-derived-classes-from-a-base-class – muhmann Jul 04 '23 at 06:27
  • 2
    FYI: Python has a documentation that also covers [`type`](https://docs.python.org/3/library/functions.html#type). – Matthias Jul 04 '23 at 06:37

2 Answers2

2

type is a class. type is a metaclass. The instances it creates are classes. In Python, classes are instances of type. If I do:

A = type("A", (), {}}

That is equivalent to:

class A:
    pass

The first argument is the .__name__ of the class, the second argument is a tuple of types to inherit from, and the third argument is the class namespace.

You can think of a class definition statement as synatic sugar for the creation of a class

This code dynamically creates a list of classes. Note, if you do something like:

Foo = type("Foo", (), {"bar": 42})

That is equivalent to:

class Foo:
    bar = 42

So, type('', (), dict(output=input))() creates a type, and the type has a single attribute, output, with a value provided by the list of inputs, then instantiates that class to create an instance of it. Consider:

>>> Foo = type("Foo", (), {"bar": 42})
>>> foo = Foo()
>>> foo.bar
42

It isn't clear why this code takes this route, since it is unnecessarily creating a class for each of these instances. More typically, you would just want:

class SomeName: # anonymous name
    def __init__(self, output):
       output = outpout

 
class MainClass:
    def some_method(self):
        ...
        self.data = [SomeName(input) for input in dnn_input_list]
    

Possibly, this was a over-engineered way of creating something like types.SimpleNamspace:

>>> import types
>>> obj = types.SimpleNamespace(foo='bar', baz=42)
>>> obj
namespace(foo='bar', baz=42)
>>> obj.foo
'bar'
>>> obj.baz
42
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
-1

The type() function in Python can be used to create new classes dynamically. It takes three arguments. The first argument is the name of the class. The second argument is a tuple of base classes. The third argument is a dictionary that defines the attributes of the class.

input_value = 10
DynamicClass = type('', (), {'output': input_value})
obj = DynamicClass()
print(obj.output)

# Output: 10