I'm trying to dynamically create subclasses in Python with type:
class A:
@classmethod
def create_subclass(cls, name, attrs):
return type(name, (cls,), attrs)
for i in range(5):
x = A.create_subclass("B", {"func": abs})
print(A.__subclasses__())
and here's what I see in the output:
[<class '__main__.B'>, <class '__main__.B'>, <class '__main__.B'>, <class '__main__.B'>, <class '__main__.B'>]
Obviously, this was not my intention. Two questions in that respect:
- How does Python handles multiple classes with identical names?
- What is a pythonic way to handle it? Of course, I can look up the name in the already existing subclasses, but then how to deal with namespaces/modules?
__subclasses__returns a list, maybe previous subclasses are not removed from there and so they stay there, also they are not the same object, I tested by adding a variable to the dict:{'var': i}so each of them have different ones. Then I iterated over the returned list and retrieved that name, they all had their own values so they are not overwritten and apparently are not deleted, so you can still use them if you need, you just apparently need to get them from that listA.__subclasses__()contains references to 5 distinct classes that just happen to have the same value for their__name__attributes.