Different classes made by type with the same name in Python?

2024/11/16 11:48:01

I was playing around with metaclasses in Python and found something very curious. I can create two classes with the same name, but that are actually different objects. See:

>>> def create_class(**data):
...     return type('MyClass', (object,), data)
... 
>>> A = create_class(x=1, y=2)
>>> B = create_class(x=1, y=2)
>>> A
<class '__main__.MyClass'>
>>> B
<class '__main__.MyClass'>
>>> A == B
False
>>> a = A()
>>> b = B()
>>> type(a)
<class '__main__.MyClass'>
>>> type(b)
<class '__main__.MyClass'>
>>> type(a) == type(b)
False

I thought names within a namespace should be unique. Is it not the case, then?

Answer

Names within a namespace are unique, but that doesn't have any bearing on your situation here. Basically there are two different things: "names" and __name__s. A "name" is a variable in a namespace. A __name__ is just an attribute of a class whose value is "what the class calls itself".

In your code above, MyClass is a __name__ and A and B are names. MyClass is not a name in the __main__ namespace. The "class __main__.MyClass" that you're seeing is just the class's __name__ attribute, not an actual variable in a namespace. Normally the class's __name__ will be equal to the name you define it with, but if you create a class programmatically by calling type as you did, it will still have a __name__ but won't necessarily be accessible via any name in the namespace.

Here's a simple example of the difference:

>>> A = type('MyClass', (object,), {})
>>> MyClass
Traceback (most recent call last):File "<pyshell#3>", line 1, in <module>MyClass
NameError: name 'MyClass' is not defined

Just passing MyClass to type doesn't actually create a variable called MyClass. It is these actual variable names that are unique, not a class's internal notion of its name.

A class is the same as another class if they are the same class object. Even if they have the same __name__ attribute, they can still be different objects.

https://en.xdnf.cn/q/71353.html

Related Q&A

Installing python server for emacs-jedi

I am trying to install Jedi for emacs using marmalade package manager by following instructions here -- http://tkf.github.io/emacs-jedi/latest/. The package manger installs Jedi along with its dependen…

Multi-feature causal CNN - Keras implementation

Im currently using a basic LSTM to make regression predictions and I would like to implement a causal CNN as it should be computationally more efficient.Im struggling to figure out how to reshape my cu…

Adding a join to an SQL Alchemy expression that already has a select_from()

Note: this is a question about SQL Alchemys expression language not the ORMSQL Alchemy is fine for adding WHERE or HAVING clauses to an existing query:q = select([bmt_gene.c.id]).select_from(bmt_gene) …

How should I move blobs from BlobStore over to Google Cloud Storage?

Our application has been running on App Engine using the Blobstore for years. We would like to move our video files over to Google Cloud Storage. What is the best practice for migrating large blobs f…

Python: Find `sys.argv` before the `sys` module is loaded

I want to find the command line arguments that my program was called with, i.e. sys.argv, but I want to do that before Python makes sys.argv available. This is because Im running code in usercustomize.…

Dotted lines instead of a missing value in matplotlib

I have an array of some data, where some of the values are missingy = np.array([np.NAN, 45, 23, np.NAN, 5, 14, 22, np.NAN, np.NAN, 18, 23])When I plot it, I have these NANs missing (which is expected)f…

How to change the creation date of file using python on a mac?

I need to update the creation time of a .mp4 file so that it will appear at the top of a list of media files sorted by creation date. I am able to easily update both the accessed and modified date of …

Classification tree in sklearn giving inconsistent answers

I am using a classification tree from sklearn and when I have the the model train twice using the same data, and predict with the same test data, I am getting different results. I tried reproducing on…

Modifying binary file with Python

i am trying to patch a hex file. i have two patch files (hex) named "patch 1" and "patch 2"the file to be patched is a 16 MB file named "file.bin".i have tried many differ…

python error : module object has no attribute AF_UNIX

this is my python code :if __name__ == __main__: import socket sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect((0.0.0.0, 4000)) import time time.sleep(2) #sock.send(1)print …