ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.1 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python |
| Last Crawled | 2026-04-08 17:38:56 (2 days ago) |
| First Indexed | 2018-01-11 23:31:35 (8 years ago) |
| HTTP Status Code | 200 |
| Meta Title | oop - What are metaclasses in Python? - Stack Overflow |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | Before delving into metaclasses, a solid grasp of Python classes is beneficial. Python holds a particularly distinctive concept of classes, a notion it adopts from the Smalltalk language. In most languages, classes are descriptions of how to create an object. That is somewhat true in Python too: >>> class ObjectCreator ( object ):
... pass >>> my_object = ObjectCreator()
>>> print (my_object)
<__main__.ObjectCreator object at 0x8974f2c >
But classes are more than that in Python. Classes are objects too. Yes, objects. When a Python script runs, every line of code is executed from top to bottom. When the Python interpreter encounters the class keyword, Python creates an object out of the "description" of the class that follows. Thus, the following instruction >>> class ObjectCreator ( object ):
... pass ...creates an object with the name ObjectCreator ! This object (the class) is itself capable of creating objects (called instances ). But still, it's an object. Therefore, like all objects: you can assign it to a variable 1 JustAnotherVariable = ObjectCreator
you can attach attributes to it ObjectCreator.class_attribute = 'foo' you can pass it as a function parameter print (ObjectCreator)
1 Note that merely assigning it to another variable doesn't change the class's __name__ , i.e., >>> print (JustAnotherVariable)
< class '__main__.ObjectCreator' >
>>> print (JustAnotherVariable())
<__main__.ObjectCreator object at 0x8997b4c >
Since classes are objects, you can create them on the fly, like any object. First, you can create a class in a function using class : >>> def choose_class ( name ):
... if name == 'foo' :
... class Foo ( object ):
... pass ... return Foo ... else :
... class Bar ( object ):
... pass ... return Bar
>>> MyClass = choose_class( 'foo' )
>>> print (MyClass)
< class '__main__.Foo' >
>>> print (MyClass())
<__main__.Foo object at 0x89c6d4c >
But it's not so dynamic, since you still have to write the whole class yourself. Since classes are objects, they must be generated by something. When you use the class keyword, Python creates this object automatically. But as
with most things in Python, it gives you a way to do it manually. Remember the function type ? The good old function that lets you know what
type an object is: >>> print ( type ( 1 ))
< class 'int' >
>>> print ( type ( "1" ))
< class 'str' >
>>> print ( type (ObjectCreator))
< class 'type' >
>>> print ( type (ObjectCreator()))
< class '__main__.ObjectCreator' >
Well, type also has a completely different ability: it can create classes on the fly. type can take the description of a class as parameters,
and return a class. (I know, it's silly that the same function can have two completely different uses according to the parameters you pass to it. It's an issue due to backward
compatibility in Python) type works this way: type (name, bases, attrs)
Where: name : name of the class bases : tuple of the parent class (for inheritance, can be empty) attrs : dictionary containing attributes names and values e.g.: >>> class MyShinyClass ( object ):
... pass can be created manually this way: >>> MyShinyClass = type ( 'MyShinyClass' , (), {}) >>> print (MyShinyClass)
< class '__main__.MyShinyClass' >
>>> print (MyShinyClass())
<__main__.MyShinyClass object at 0x8997cec >
You'll notice that we use MyShinyClass as the name of the class
and as the variable to hold the class reference. They can be different,
but there is no reason to complicate things. type accepts a dictionary to define the attributes of the class. So: >>> class Foo ( object ):
... bar = True Can be translated to: >>> Foo = type ( 'Foo' , (), { 'bar' : True })
And used as a normal class: >>> print (Foo)
< class '__main__.Foo' >
>>> print (Foo.bar)
True >>> f = Foo()
>>> print (f)
<__main__.Foo object at 0x8a9b84c >
>>> print (f.bar)
True And of course, you can inherit from it, so: >>> class FooChild ( Foo ):
... pass would be: >>> FooChild = type ( 'FooChild' , (Foo,), {})
>>> print (FooChild)
< class '__main__.FooChild' >
>>> print (FooChild.bar) True Eventually, you'll want to add methods to your class. Just define a function
with the proper signature and assign it as an attribute. >>> def echo_bar ( self ):
... print (self.bar)
>>> FooChild = type ( 'FooChild' , (Foo,), { 'echo_bar' : echo_bar})
>>> hasattr (Foo, 'echo_bar' )
False >>> hasattr (FooChild, 'echo_bar' )
True >>> my_foo = FooChild()
>>> my_foo.echo_bar()
True And you can add even more methods after you dynamically create the class, just like adding methods to a normally created class object. >>> def echo_bar_more ( self ):
... print ( 'yet another method' )
>>> FooChild.echo_bar_more = echo_bar_more
>>> hasattr (FooChild, 'echo_bar_more' )
True You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically. This is what Python does when you use the keyword class , and it does so by using a metaclass. Metaclasses are the 'stuff' that creates classes. You define classes in order to create objects, right? But we learned that Python classes are objects. Well, metaclasses are what create these objects. They are the classes' classes,
you can picture them this way: MyClass = MetaClass()
my_object = MyClass()
You've seen that type lets you do something like this: MyClass = type ( 'MyClass' , (), {})
It's because the function type is in fact a metaclass. type is the
metaclass Python uses to create all classes behind the scenes. Now you wonder "why the heck is it written in lowercase, and not Type ?" Well, I guess it's a matter of consistency with str , the class that creates
strings objects, and int the class that creates integer objects. type is
just the class that creates class objects. You see that by checking the __class__ attribute. Everything, and I mean everything, is an object in Python. That includes integers,
strings, functions and classes. All of them are objects. And all of them have
been created from a class: >>> age = 35 >>> age.__class__
< type 'int' >
>>> name = 'bob' >>> name.__class__
< type 'str' >
>>> def foo (): pass >>> foo.__class__
< type 'function' >
>>> class Bar ( object ): pass >>> b = Bar()
>>> b.__class__
< class '__main__.Bar' >
Now, what is the __class__ of any __class__ ? >>> age.__class__.__class__
< type 'type' >
>>> name.__class__.__class__
< type 'type' >
>>> foo.__class__.__class__
< type 'type' >
>>> b.__class__.__class__
< type 'type' >
So, a metaclass is just the stuff that creates class objects. You can call it a 'class factory' if you wish. type is the built-in metaclass Python uses, but of course, you can create your
own metaclass. In Python 2, you can add a __metaclass__ attribute when you write a class (see next section for the Python 3 syntax): class Foo ( object ):
__metaclass__ = something...
[...]
If you do so, Python will use the metaclass to create the class Foo . Careful, it's tricky. You write class Foo(object) first, but the class object Foo is not created
in memory yet. Python will look for __metaclass__ in the class definition. If it finds it,
it will use it to create the class object Foo . If it doesn't, it will use
type to create the class. Read that several times. When you do: class Foo ( Bar ):
pass Python does the following: Is there a __metaclass__ attribute in Foo ? If yes, create in-memory a class object (I said a class object, stay with me here), with the name Foo by using what is in __metaclass__ . If Python can't find __metaclass__ , it will look for a __metaclass__ at the MODULE level, and try to do the same (but only for classes that don't inherit anything, basically old-style classes). Then if it can't find any __metaclass__ at all, it will use the Bar 's (the first parent) own metaclass (which might be the default type ) to create the class object. Be careful here that the __metaclass__ attribute will not be inherited, the metaclass of the parent ( Bar.__class__ ) will be. If Bar used a __metaclass__ attribute that created Bar with type() (and not type.__new__() ), the subclasses will not inherit that behavior. Now the big question is, what can you put in __metaclass__ ? The answer is something that can create a class. And what can create a class? type , or anything that subclasses or uses it. The syntax to set the metaclass has been changed in Python 3: class Foo ( object , metaclass=something):
...
i.e. the __metaclass__ attribute is no longer used, in favor of a keyword argument in the list of base classes. The behavior of metaclasses however stays largely the same . One thing added to metaclasses in Python 3 is that you can also pass attributes as keyword-arguments into a metaclass, like so: class Foo ( object , metaclass=something, kwarg1=value1, kwarg2=value2):
...
Read the section below for how Python handles this. The main purpose of a metaclass is to change the class automatically,
when it's created. You usually do this for APIs, where you want to create classes matching the
current context. Imagine a stupid example, where you decide that all classes in your module
should have their attributes written in uppercase. There are several ways to
do this, but one way is to set __metaclass__ at the module level. This way, all classes of this module will be created using this metaclass,
and we just have to tell the metaclass to turn all attributes to uppercase. Luckily, __metaclass__ can actually be any callable, it doesn't need to be a
formal class (I know, something with 'class' in its name doesn't need to be
a class, go figure... but it's helpful). So we will start with a simple example, by using a function. def upper_attr ( future_class_name, future_class_parents, future_class_attrs ):
"""
Return a class object, with the list of its attribute turned
into uppercase.
"""
uppercase_attrs = {
attr if attr.startswith( "__" ) else attr.upper(): v
for attr, v in future_class_attrs.items()
}
return type (future_class_name, future_class_parents, uppercase_attrs)
__metaclass__ = upper_attr class Foo ():
bar = 'bip' Let's check: >>> hasattr (Foo, 'bar' )
False >>> hasattr (Foo, 'BAR' )
True >>> Foo.BAR
'bip' Now, let's do exactly the same, but using a real class for a metaclass: class UpperAttrMetaclass ( type ):
def __new__ (
upperattr_metaclass,
future_class_name,
future_class_parents,
future_class_attrs
):
uppercase_attrs = {
attr if attr.startswith( "__" ) else attr.upper(): v
for attr, v in future_class_attrs.items()
}
return type (future_class_name, future_class_parents, uppercase_attrs)
Let's rewrite the above, but with shorter and more realistic variable names now that we know what they mean: class UpperAttrMetaclass ( type ):
def __new__ ( cls, clsname, bases, attrs ):
uppercase_attrs = {
attr if attr.startswith( "__" ) else attr.upper(): v
for attr, v in attrs.items()
}
return type (clsname, bases, uppercase_attrs)
You may have noticed the extra argument cls . There is
nothing special about it: __new__ always receives the class it's defined in, as the first parameter. Just like you have self for ordinary methods which receive the instance as the first parameter, or the defining class for class methods. But this is not proper OOP. We are calling type directly and we aren't overriding or calling the parent's __new__ . Let's do that instead: class UpperAttrMetaclass ( type ):
def __new__ ( cls, clsname, bases, attrs ):
uppercase_attrs = {
attr if attr.startswith( "__" ) else attr.upper(): v
for attr, v in attrs.items()
}
return type .__new__(cls, clsname, bases, uppercase_attrs)
We can make it even cleaner by using super , which will ease inheritance (because yes, you can have metaclasses, inheriting from metaclasses, inheriting from type): class UpperAttrMetaclass ( type ):
def __new__ ( cls, clsname, bases, attrs ):
uppercase_attrs = {
attr if attr.startswith( "__" ) else attr.upper(): v
for attr, v in attrs.items()
}
return super (UpperAttrMetaclass, cls).__new__(
cls, clsname, bases, uppercase_attrs)
return super ().__new__(cls, clsname, bases, uppercase_attrs)
Oh, and in Python 3 if you do this call with keyword arguments, like this: class Foo ( object , metaclass=MyMetaclass, kwarg1=value1):
...
It translates to this in the metaclass to use it: class MyMetaclass ( type ):
def __new__ ( cls, clsname, bases, dct, kwarg1=default ):
...
That's it. There is really nothing more about metaclasses. The reason behind the complexity of the code using metaclasses is not because
of metaclasses, it's because you usually use metaclasses to do twisted stuff
relying on introspection, manipulating inheritance, vars such as __dict__ , etc. Indeed, metaclasses are especially useful to do black magic, and therefore
complicated stuff. But by themselves, they are simple: intercept a class creation modify the class return the modified class Since __metaclass__ can accept any callable, why would you use a class
since it's obviously more complicated? There are several reasons to do so: The intention is clear. When you read UpperAttrMetaclass(type) , you know
what's going to follow You can use OOP. Metaclass can inherit from metaclass, override parent methods. Metaclasses can even use metaclasses. Subclasses of a class will be instances of its metaclass if you specified a metaclass-class, but not with a metaclass-function. You can structure your code better. You never use metaclasses for something as trivial as the above example. It's usually for something complicated. Having the ability to make several methods and group them in one class is very useful to make the code easier to read. You can hook on __new__ , __init__ and __call__ . Which will allow you to do different stuff, Even if usually you can do it all in __new__ ,
some people are just more comfortable using __init__ . These are called metaclasses, damn it! It must mean something! Now the big question. Why would you use some obscure error-prone feature? Well, usually you don't: Metaclasses are deeper magic that
99% of users should never worry about it.
If you wonder whether you need them,
you don't (the people who actually
need them know with certainty that
they need them, and don't need an
explanation about why). Python Guru Tim Peters The main use case for a metaclass is creating an API. A typical example of this is the Django ORM. It allows you to define something like this: class Person (models.Model):
name = models.CharField(max_length= 30 )
age = models.IntegerField()
But if you do this: person = Person(name= 'bob' , age= '35' )
print (person.age)
It won't return an IntegerField object. It will return an int , and can even take it directly from the database. This is possible because models.Model defines __metaclass__ and
it uses some magic that will turn the Person you just defined with simple statements
into a complex hook to a database field. Django makes something complex look simple by exposing a simple API
and using metaclasses, recreating code from this API to do the real job
behind the scenes. First, you know that classes are objects that can create instances. Well, in fact, classes are themselves instances. Of metaclasses. >>> class Foo ( object ): pass >>> id (Foo)
142630324 Everything is an object in Python, and they are all either instance of classes
or instances of metaclasses. Except for type . type is actually its own metaclass. This is not something you could
reproduce in pure Python, and is done by cheating a little bit at the implementation
level. Secondly, metaclasses are complicated. You may not want to use them for
very simple class alterations. You can change classes by using two different techniques: 99% of the time you need class alteration, you are better off using these. But 98% of the time, you don't need class alteration at all. |
| Markdown | # 
By clicking “Sign up”, you agree to our [terms of service](https://stackoverflow.com/legal/terms-of-service/public) and acknowledge you have read our [privacy policy](https://stackoverflow.com/legal/privacy-policy).
# OR
Already have an account? [Log in](https://stackoverflow.com/users/login)
[Skip to main content](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#content)
[Stack Overflow](https://stackoverflow.com/)
1. [About](https://stackoverflow.co/)
2. Products
3. [For Teams](https://stackoverflow.co/internal/)
1. [Stack Internal Implement a knowledge platform layer to power your enterprise and AI tools.](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-for-teams)
2. [Stack Data Licensing Get access to top-class technical expertise with trusted & attributed content.](https://stackoverflow.co/data-licensing/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=overflow-api)
3. [Stack Ads Connect your brand to the world’s most trusted technologist communities.](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-advertising)
4. [Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal.](https://stackoverflow.blog/releases/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=releases)
5. [About the company](https://stackoverflow.co/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=about-the-company) [Visit the blog](https://stackoverflow.blog/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=blog)
1. ### [current community](https://stackoverflow.com/)
- [Stack Overflow](https://stackoverflow.com/)
[help](https://stackoverflow.com/help) [chat](https://chat.stackoverflow.com/?tab=explore)
- [Meta Stack Overflow](https://meta.stackoverflow.com/)
### your communities
[Sign up](https://stackoverflow.com/users/signup?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F100003%2Fwhat-are-metaclasses-in-python) or [log in](https://stackoverflow.com/users/login?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F100003%2Fwhat-are-metaclasses-in-python) to customize your list.
### [more stack exchange communities](https://stackexchange.com/sites)
[company blog](https://stackoverflow.blog/)
2. [Log in](https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F100003%2Fwhat-are-metaclasses-in-python)
3. [Sign up](https://stackoverflow.com/users/signup?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F100003%2Fwhat-are-metaclasses-in-python)
# Let's set up your homepage Select a few topics you're interested in:
python
javascript
c\#
reactjs
java
android
html
flutter
c++
node.js
typescript
css
r
php
angular
next.js
spring-boot
machine-learning
sql
excel
ios
azure
docker
Or search from our full list:
- javascript
- python
- java
- c\#
- php
- android
- html
- jquery
- c++
- css
- ios
- sql
- mysql
- r
- reactjs
- node.js
- arrays
- c
- asp.net
- json
- python-3.x
- .net
- ruby-on-rails
- sql-server
- swift
- django
- angular
- objective-c
- excel
- pandas
- angularjs
- regex
- typescript
- ruby
- linux
- ajax
- iphone
- vba
- xml
- laravel
- spring
- asp.net-mvc
- database
- wordpress
- string
- flutter
- postgresql
- mongodb
- wpf
- windows
- xcode
- amazon-web-services
- bash
- git
- oracle-database
- spring-boot
- dataframe
- azure
- firebase
- list
- multithreading
- docker
- vb.net
- react-native
- eclipse
- algorithm
- powershell
- macos
- visual-studio
- numpy
- image
- forms
- scala
- function
- vue.js
- performance
- twitter-bootstrap
- selenium
- winforms
- kotlin
- loops
- express
- dart
- hibernate
- sqlite
- matlab
- python-2.7
- shell
- rest
- apache
- entity-framework
- android-studio
- csv
- maven
- linq
- qt
- dictionary
- unit-testing
- asp.net-core
- facebook
- apache-spark
- tensorflow
- file
- swing
- class
- unity-game-engine
- sorting
- date
- authentication
- go
- symfony
- t-sql
- opencv
- matplotlib
- .htaccess
- google-chrome
- for-loop
- datetime
- codeigniter
- perl
- http
- validation
- sockets
- google-maps
- object
- uitableview
- xaml
- oop
- visual-studio-code
- if-statement
- cordova
- ubuntu
- web-services
- email
- android-layout
- github
- spring-mvc
- elasticsearch
- kubernetes
- selenium-webdriver
- ms-access
- ggplot2
- user-interface
- parsing
- pointers
- google-sheets
- c++11
- security
- machine-learning
- google-apps-script
- ruby-on-rails-3
- templates
- flask
- nginx
- variables
- exception
- sql-server-2008
- gradle
- debugging
- tkinter
- delphi
- listview
- jpa
- asynchronous
- web-scraping
- haskell
- pdf
- jsp
- ssl
- amazon-s3
- google-cloud-platform
- testing
- jenkins
- xamarin
- wcf
- batch-file
- generics
- npm
- ionic-framework
- network-programming
- unix
- recursion
- google-app-engine
- mongoose
- visual-studio-2010
- .net-core
- android-fragments
- assembly
- animation
- math
- svg
- rust
- session
- intellij-idea
- hadoop
- join
- curl
- winapi
- django-models
- next.js
- laravel-5
- url
- heroku
- http-redirect
- tomcat
- google-cloud-firestore
- inheritance
- webpack
- gcc
- image-processing
- swiftui
- keras
- asp.net-mvc-4
- logging
- dom
- matrix
- pyspark
- actionscript-3
- button
- post
- optimization
- firebase-realtime-database
- web
- jquery-ui
- cocoa
- xpath
- iis
- d3.js
- javafx
- firefox
- xslt
- internet-explorer
- caching
- select
- asp.net-mvc-3
- opengl
- events
- asp.net-web-api
- plot
- dplyr
- encryption
- magento
- stored-procedures
- search
- amazon-ec2
- ruby-on-rails-4
- memory
- canvas
- multidimensional-array
- audio
- random
- jsf
- vector
- redux
- cookies
- input
- facebook-graph-api
- flash
- indexing
- xamarin.forms
- arraylist
- ipad
- cocoa-touch
- data-structures
- video
- model-view-controller
- azure-devops
- serialization
- apache-kafka
- jdbc
- razor
- woocommerce
- awk
- routes
- servlets
- mod-rewrite
- excel-formula
- beautifulsoup
- filter
- iframe
- docker-compose
- design-patterns
- aws-lambda
- text
- visual-c++
- django-rest-framework
- cakephp
- mobile
- android-intent
- struct
- react-hooks
- methods
- groovy
- mvvm
- lambda
- ssh
- checkbox
- time
- ecmascript-6
- grails
- google-chrome-extension
- installation
- cmake
- sharepoint
- shiny
- spring-security
- jakarta-ee
- plsql
- android-recyclerview
- core-data
- types
- sed
- meteor
- android-activity
- bootstrap-4
- activerecord
- websocket
- graph
- replace
- group-by
- scikit-learn
- vim
- file-upload
- boost
- junit
- memory-management
- sass
- async-await
- import
- deep-learning
- error-handling
- eloquent
- dynamic
- soap
- dependency-injection
- silverlight
- layout
- apache-spark-sql
- charts
- deployment
- browser
- gridview
- svn
- while-loop
- google-bigquery
- vuejs2
- highcharts
- dll
- ffmpeg
- view
- foreach
- makefile
- plugins
- redis
- c\#-4.0
- reporting-services
- jupyter-notebook
- unicode
- merge
- reflection
- https
- server
- google-maps-api-3
- twitter
- oauth-2.0
- extjs
- terminal
- axios
- pip
- split
- cmd
- pytorch
- encoding
- django-views
- collections
- database-design
- hash
- netbeans
- automation
- data-binding
- ember.js
- build
- tcp
- pdo
- sqlalchemy
- apache-flex
- entity-framework-core
- concurrency
- mysqli
- command-line
- spring-data-jpa
- printing
- react-redux
- java-8
- lua
- html-table
- neo4j
- ansible
- service
- jestjs
- parameters
- enums
- flexbox
- material-ui
- module
- promise
- visual-studio-2012
- outlook
- web-applications
- firebase-authentication
- webview
- uwp
- jquery-mobile
- utf-8
- datatable
- python-requests
- parallel-processing
- colors
- drop-down-menu
- scipy
- scroll
- tfs
- hive
- count
- syntax
- ms-word
- twitter-bootstrap-3
- ssis
- fonts
- rxjs
- constructor
- google-analytics
- file-io
- paypal
- three.js
- powerbi
- graphql
- cassandra
- discord
- graphics
- compiler-errors
- gwt
- socket.io
- react-router
- backbone.js
- solr
- memory-leaks
- url-rewriting
- datatables
- nlp
- terraform
- oauth
- datagridview
- drupal
- zend-framework
- oracle11g
- triggers
- knockout.js
- neural-network
- interface
- django-forms
- angular-material
- casting
- jmeter
- linked-list
- google-api
- path
- timer
- arduino
- django-templates
- orm
- proxy
- directory
- windows-phone-7
- parse-platform
- visual-studio-2015
- cron
- conditional-statements
- push-notification
- functional-programming
- primefaces
- pagination
- model
- jar
- xamarin.android
- hyperlink
- uiview
- vbscript
- visual-studio-2013
- google-cloud-functions
- azure-active-directory
- gitlab
- jwt
- download
- swift3
- sql-server-2005
- process
- pygame
- configuration
- rspec
- properties
- callback
- combobox
- windows-phone-8
- linux-kernel
- safari
- scrapy
- permissions
- emacs
- x86
- clojure
- scripting
- raspberry-pi
- io
- scope
- azure-functions
- expo
- compilation
- responsive-design
- mongodb-query
- nhibernate
- angularjs-directive
- reference
- request
- binding
- bluetooth
- dns
- architecture
- playframework
- pyqt
- 3d
- version-control
- discord.js
- doctrine-orm
- package
- f\#
- rubygems
- get
- sql-server-2012
- autocomplete
- tree
- openssl
- datepicker
- kendo-ui
- jackson
- yii
- controller
- grep
- nested
- xamarin.ios
- static
- null
- transactions
- statistics
- active-directory
- datagrid
- dockerfile
- uiviewcontroller
- webforms
- sas
- discord.py
- computer-vision
- phpmyadmin
- notifications
- duplicates
- mocking
- pycharm
- youtube
- yaml
- nullpointerexception
- menu
- blazor
- sum
- plotly
- bitmap
- visual-studio-2008
- asp.net-mvc-5
- floating-point
- yii2
- css-selectors
- stl
- electron
- android-listview
- jsf-2
- time-series
- cryptography
- ant
- hashmap
- character-encoding
- stream
- msbuild
- asp.net-core-mvc
- sdk
- google-drive-api
- jboss
- selenium-chromedriver
- joomla
- devise
- navigation
- cors
- cuda
- anaconda
- frontend
- background
- multiprocessing
- binary
- pyqt5
- camera
- iterator
- linq-to-sql
- mariadb
- onclick
- android-jetpack-compose
- ios7
- microsoft-graph-api
- android-asynctask
- rabbitmq
- tabs
- amazon-dynamodb
- laravel-4
- environment-variables
- uicollectionview
- insert
- linker
- xsd
- coldfusion
- console
- continuous-integration
- upload
- textview
- ftp
- opengl-es
- macros
- operating-system
- mockito
- localization
- formatting
- xml-parsing
- json.net
- vuejs3
- type-conversion
- data.table
- kivy
- timestamp
- integer
- calendar
- segmentation-fault
- android-ndk
- prolog
- drag-and-drop
- char
- crash
- jasmine
- automated-tests
- geometry
- azure-pipelines
- dependencies
- fortran
- android-gradle-plugin
- itext
- sprite-kit
- mfc
- header
- attributes
- firebase-cloud-messaging
- nosql
- format
- nuxt.js
- odoo
- db2
- jquery-plugins
- event-handling
- julia
- jenkins-pipeline
- leaflet
- annotations
- nestjs
- flutter-layout
- keyboard
- postman
- textbox
- arm
- visual-studio-2017
- stripe-payments
- gulp
- libgdx
- uikit
- synchronization
- timezone
- azure-web-app-service
- dom-events
- xampp
- wso2
- crystal-reports
- google-sheets-formula
- namespaces
- aggregation-framework
- swagger
- android-emulator
- uiscrollview
- jvm
- sequelize.js
- chart.js
- com
- snowflake-cloud-data-platform
- subprocess
- geolocation
- webdriver
- html5-canvas
- garbage-collection
- sql-update
- centos
- dialog
- concatenation
- numbers
- widget
- qml
- tuples
- set
- java-stream
- mapreduce
- ionic2
- smtp
- windows-10
- rotation
- android-edittext
- modal-dialog
- nuget
- spring-data
- radio-button
- doctrine
- http-headers
- grid
- lucene
- sonarqube
- xmlhttprequest
- listbox
- switch-statement
- initialization
- internationalization
- components
- boolean
- apache-camel
- google-play
- gdb
- serial-port
- ios5
- ldap
- return
- youtube-api
- pivot
- latex
- eclipse-plugin
- tags
- frameworks
- containers
- c++17
- github-actions
- subquery
- dataset
- asp-classic
- embedded
- foreign-keys
- label
- uinavigationcontroller
- delegates
- copy
- struts2
- google-cloud-storage
- migration
- protractor
- base64
- queue
- uibutton
- find
- sql-server-2008-r2
- arguments
- composer-php
- append
- jaxb
- stack
- tailwind-css
- zip
- cucumber
- autolayout
- ide
- entity-framework-6
- iteration
- popup
- r-markdown
- windows-7
- vb6
- airflow
- g++
- ssl-certificate
- clang
- hover
- jqgrid
- range
- gmail
Next
You’ll be prompted to create an account to view your personalized homepage.
1. 1. [Home](https://stackoverflow.com/)
2. [Questions](https://stackoverflow.com/questions)
3. [AI Assist](https://stackoverflow.com/ai-assist)
4. [Tags](https://stackoverflow.com/tags)
5. [Challenges](https://stackoverflow.com/beta/challenges)
6. [Chat](https://chat.stackoverflow.com/rooms/259507/stack-overflow-lobby)
7. [Articles](https://stackoverflow.blog/contributed?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=so-blog&utm_content=experiment-articles)
8. [Users](https://stackoverflow.com/users)
9. [Companies](https://stackoverflow.com/jobs/companies?so_medium=stackoverflow&so_source=SiteNav)
10. [Collectives]()
11. Communities for your favorite technologies. [Explore all Collectives](https://stackoverflow.com/collectives-all)
2. Stack Internal
Stack Overflow for Teams is now called **Stack Internal**. Bring the best of human thought and AI automation together at your work.
[Try for free](https://stackoverflowteams.com/teams/create/free/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams) [Learn more](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams)
3. [Stack Internal]()
4. Bring the best of human thought and AI automation together at your work. [Learn more](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact)
##### Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
[Learn more about Collectives](https://stackoverflow.com/collectives)
**Stack Internal**
Knowledge at work
Bring the best of human thought and AI automation together at your work.
[Explore Stack Internal](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact-popover)
# [What are metaclasses in Python?](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python)
[Ask Question](https://stackoverflow.com/questions/ask)
Asked
17 years, 3 months ago
Modified [4 months ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python?lastactivity "2025-08-01 05:49:44Z")
Viewed 1.2m times
This question shows research effort; it is useful and clear
7519
Save this question.
Show activity on this post.
What are [metaclasses](https://docs.python.org/3/reference/datamodel.html#metaclasses)? What are they used for?
- [python](https://stackoverflow.com/questions/tagged/python "show questions tagged 'python'")
- [oop](https://stackoverflow.com/questions/tagged/oop "show questions tagged 'oop'")
- [metaclass](https://stackoverflow.com/questions/tagged/metaclass "show questions tagged 'metaclass'")
- [python-class](https://stackoverflow.com/questions/tagged/python-class "show questions tagged 'python-class'")
- [python-datamodel](https://stackoverflow.com/questions/tagged/python-datamodel "show questions tagged 'python-datamodel'")
[Share](https://stackoverflow.com/q/100003 "Short permalink to this question")
Share a link to this question
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this question](https://stackoverflow.com/posts/100003/edit)
Follow
Follow this question to receive notifications
[edited Feb 8, 2023 at 4:49](https://stackoverflow.com/posts/100003/revisions "show all edits to this post")
[](https://stackoverflow.com/users/365102/mateen-ulhaq)
[Mateen Ulhaq](https://stackoverflow.com/users/365102/mateen-ulhaq)
27\.9k2121 gold badges122122 silver badges155155 bronze badges
asked Sep 19, 2008 at 6:10
[](https://stackoverflow.com/users/9951/bite-code)
[Bite code](https://stackoverflow.com/users/9951/bite-code)
601k118118 gold badges310310 silver badges336336 bronze badges
1
- I see a class as a *human-readable documentation* of a given data-structure. It's time to create a class when (A) it is used in multiple modules and (B) it has a complex and/or non-obvious structure. Why make a Vec3D class when using a list \[x,y,z\] is so simple? But a Car object with wheels engine chassis etc is a different story. Dynamic class creation is seldom needed if you follow this philosophy. But Python is a *very* dynamic language and so it is *possible* to do so. Modules are also dynamic in interesting but rarely-used ways.
Kevin Kostlan
– [Kevin Kostlan](https://stackoverflow.com/users/412234/kevin-kostlan "3,589 reputation")
2024-01-13 07:00:52 +00:00
[Commented Jan 13, 2024 at 7:00](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment137174276_100003)
[Add a comment](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python "Use comments to ask for more information or suggest improvements. Avoid answering questions in comments.") \|
## 26 Answers 26
Sorted by:
[Reset to default](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python?answertab=scoredesc#tab-top)
This answer is useful
9309
Save this answer.
\+250
This answer has been awarded bounties worth 250 reputation by Martijn Pieters, Rohit Jain and U13-Forward
Show activity on this post.
# Classes are objects
Before delving into metaclasses, a solid grasp of Python classes is beneficial. Python holds a particularly distinctive concept of classes, a notion it adopts from the Smalltalk language.
In most languages, classes are descriptions of how to create an object. That is somewhat true in Python too:
```
Copy
```
But classes are more than that in Python. **Classes are objects too.**
Yes, objects.
When a Python script runs, every line of code is executed from top to bottom. When the Python interpreter encounters the `class` keyword, Python creates an **object** out of the "description" of the class that follows. Thus, the following instruction
```
Copy
```
...creates an *object* with the name `ObjectCreator`\!
This object (the class) is itself capable of creating objects (called *instances*).
But still, it's an object. Therefore, like all objects:
- you can assign it to a variable1
```
CopyJustAnotherVariable = ObjectCreator
```
- you can attach attributes to it
```
CopyObjectCreator.class_attribute = 'foo'
```
- you can pass it as a function parameter
```
Copyprint(ObjectCreator)
```
1 Note that merely assigning it to another variable doesn't change the class's `__name__`, i.e.,
```
Copy
```
# Creating classes dynamically
Since classes are objects, you can create them on the fly, like any object.
First, you can create a class in a function using `class`:
```
Copy
```
But it's not so dynamic, since you still have to write the whole class yourself.
Since classes are objects, they must be generated by something.
When you use the `class` keyword, Python creates this object automatically. But as with most things in Python, it gives you a way to do it manually.
Remember the function `type`? The good old function that lets you know what type an object is:
```
Copy
```
Well, [`type`](http://docs.python.org/2/library/functions.html#type) also has a completely different ability: it can create classes on the fly. `type` can take the description of a class as parameters, and return a class.
(I know, it's silly that the same function can have two completely different uses according to the parameters you pass to it. It's an issue due to backward compatibility in Python)
`type` works this way:
```
Copytype(name, bases, attrs)
```
Where:
- **`name`**: name of the class
- **`bases`**: tuple of the parent class (for inheritance, can be empty)
- **`attrs`**: dictionary containing attributes names and values
e.g.:
```
Copy
```
can be created manually this way:
```
Copy
```
You'll notice that we use `MyShinyClass` as the name of the class and as the variable to hold the class reference. They can be different, but there is no reason to complicate things.
`type` accepts a dictionary to define the attributes of the class. So:
```
Copy
```
Can be translated to:
```
Copy>>> Foo = type('Foo', (), {'bar':True})
```
And used as a normal class:
```
Copy
```
And of course, you can inherit from it, so:
```
Copy
```
would be:
```
Copy
```
Eventually, you'll want to add methods to your class. Just define a function with the proper signature and assign it as an attribute.
```
Copy
```
And you can add even more methods after you dynamically create the class, just like adding methods to a normally created class object.
```
Copy
```
You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically.
This is what Python does when you use the keyword `class`, and it does so by using a metaclass.
# What are metaclasses (finally)
Metaclasses are the 'stuff' that creates classes.
You define classes in order to create objects, right?
But we learned that Python classes are objects.
Well, metaclasses are what create these objects. They are the classes' classes, you can picture them this way:
```
Copy
```
You've seen that `type` lets you do something like this:
```
CopyMyClass = type('MyClass', (), {})
```
It's because the function `type` is in fact a metaclass. `type` is the metaclass Python uses to create all classes behind the scenes.
Now you wonder "why the heck is it written in lowercase, and not `Type`?"
Well, I guess it's a matter of consistency with `str`, the class that creates strings objects, and `int` the class that creates integer objects. `type` is just the class that creates class objects.
You see that by checking the `__class__` attribute.
Everything, and I mean everything, is an object in Python. That includes integers, strings, functions and classes. All of them are objects. And all of them have been created from a class:
```
Copy
```
Now, what is the `__class__` of any `__class__` ?
```
Copy
```
So, a metaclass is just the stuff that creates class objects.
You can call it a 'class factory' if you wish.
`type` is the built-in metaclass Python uses, but of course, you can create your own metaclass.
# The [`__metaclass__`](http://docs.python.org/2/reference/datamodel.html?highlight=__metaclass__#__metaclass__) attribute
In Python 2, you can add a `__metaclass__` attribute when you write a class (see next section for the Python 3 syntax):
```
Copy
```
If you do so, Python will use the metaclass to create the class `Foo`.
Careful, it's tricky.
You write `class Foo(object)` first, but the class object `Foo` is not created in memory yet.
Python will look for `__metaclass__` in the class definition. If it finds it, it will use it to create the class object `Foo`. If it doesn't, it will use `type` to create the class.
Read that several times.
When you do:
```
Copy
```
Python does the following:
Is there a `__metaclass__` attribute in `Foo`?
If yes, create in-memory a class object (I said a class object, stay with me here), with the name `Foo` by using what is in `__metaclass__`.
If Python can't find `__metaclass__`, it will look for a `__metaclass__` at the MODULE level, and try to do the same (but only for classes that don't inherit anything, basically old-style classes).
Then if it can't find any `__metaclass__` at all, it will use the `Bar`'s (the first parent) own metaclass (which might be the default `type`) to create the class object.
Be careful here that the `__metaclass__` attribute will not be inherited, the metaclass of the parent (`Bar.__class__`) will be. If `Bar` used a `__metaclass__` attribute that created `Bar` with `type()` (and not `type.__new__()`), the subclasses will not inherit that behavior.
Now the big question is, what can you put in `__metaclass__`?
The answer is something that can create a class.
And what can create a class? `type`, or anything that subclasses or uses it.
# Metaclasses in Python 3
The syntax to set the metaclass has been changed in Python 3:
```
Copy
```
i.e. the `__metaclass__` attribute is no longer used, in favor of a keyword argument in the list of base classes.
The behavior of metaclasses however stays [largely the same](https://www.python.org/dev/peps/pep-3115/).
One thing added to metaclasses in Python 3 is that you can also pass attributes as keyword-arguments into a metaclass, like so:
```
Copy
```
Read the section below for how Python handles this.
# Custom metaclasses
The main purpose of a metaclass is to change the class automatically, when it's created.
You usually do this for APIs, where you want to create classes matching the current context.
Imagine a stupid example, where you decide that all classes in your module should have their attributes written in uppercase. There are several ways to do this, but one way is to set `__metaclass__` at the module level.
This way, all classes of this module will be created using this metaclass, and we just have to tell the metaclass to turn all attributes to uppercase.
Luckily, `__metaclass__` can actually be any callable, it doesn't need to be a formal class (I know, something with 'class' in its name doesn't need to be a class, go figure... but it's helpful).
So we will start with a simple example, by using a function.
```
Copy
```
Let's check:
```
Copy
```
Now, let's do exactly the same, but using a real class for a metaclass:
```
Copy
```
Let's rewrite the above, but with shorter and more realistic variable names now that we know what they mean:
```
Copy
```
You may have noticed the extra argument `cls`. There is nothing special about it: `__new__` always receives the class it's defined in, as the first parameter. Just like you have `self` for ordinary methods which receive the instance as the first parameter, or the defining class for class methods.
But this is not proper OOP. We are calling `type` directly and we aren't overriding or calling the parent's `__new__`. Let's do that instead:
```
Copy
```
We can make it even cleaner by using `super`, which will ease inheritance (because yes, you can have metaclasses, inheriting from metaclasses, inheriting from type):
```
Copy
```
Oh, and in Python 3 if you do this call with keyword arguments, like this:
```
Copy
```
It translates to this in the metaclass to use it:
```
Copy
```
That's it. There is really nothing more about metaclasses.
The reason behind the complexity of the code using metaclasses is not because of metaclasses, it's because you usually use metaclasses to do twisted stuff relying on introspection, manipulating inheritance, vars such as `__dict__`, etc.
Indeed, metaclasses are especially useful to do black magic, and therefore complicated stuff. But by themselves, they are simple:
- intercept a class creation
- modify the class
- return the modified class
# Why would you use metaclasses classes instead of functions?
Since `__metaclass__` can accept any callable, why would you use a class since it's obviously more complicated?
There are several reasons to do so:
- The intention is clear. When you read `UpperAttrMetaclass(type)`, you know what's going to follow
- You can use OOP. Metaclass can inherit from metaclass, override parent methods. Metaclasses can even use metaclasses.
- Subclasses of a class will be instances of its metaclass if you specified a metaclass-class, but not with a metaclass-function.
- You can structure your code better. You never use metaclasses for something as trivial as the above example. It's usually for something complicated. Having the ability to make several methods and group them in one class is very useful to make the code easier to read.
- You can hook on `__new__`, `__init__` and `__call__`. Which will allow you to do different stuff, Even if usually you can do it all in `__new__`, some people are just more comfortable using `__init__`.
- These are called metaclasses, damn it! It must mean something\!
# Why would you use metaclasses?
Now the big question. Why would you use some obscure error-prone feature?
Well, usually you don't:
> Metaclasses are deeper magic that 99% of users should never worry about it. If you wonder whether you need them, you don't (the people who actually need them know with certainty that they need them, and don't need an explanation about why).
*Python Guru Tim Peters*
The main use case for a metaclass is creating an API. A typical example of this is the Django ORM. It allows you to define something like this:
```
Copy
```
But if you do this:
```
Copy
```
It won't return an `IntegerField` object. It will return an `int`, and can even take it directly from the database.
This is possible because `models.Model` defines `__metaclass__` and it uses some magic that will turn the `Person` you just defined with simple statements into a complex hook to a database field.
Django makes something complex look simple by exposing a simple API and using metaclasses, recreating code from this API to do the real job behind the scenes.
# The last word
First, you know that classes are objects that can create instances.
Well, in fact, classes are themselves instances. Of metaclasses.
```
Copy
```
Everything is an object in Python, and they are all either instance of classes or instances of metaclasses.
Except for `type`.
`type` is actually its own metaclass. This is not something you could reproduce in pure Python, and is done by cheating a little bit at the implementation level.
Secondly, metaclasses are complicated. You may not want to use them for very simple class alterations. You can change classes by using two different techniques:
- [monkey patching](http://en.wikipedia.org/wiki/Monkey_patch)
- class decorators
99% of the time you need class alteration, you are better off using these.
But 98% of the time, you don't need class alteration at all.
[Share](https://stackoverflow.com/a/6581949 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/6581949/edit)
Follow
Follow this answer to receive notifications
[edited Aug 1 at 5:49](https://stackoverflow.com/posts/6581949/revisions "show all edits to this post")
community wiki
[72 revs, 54 users 61%](https://stackoverflow.com/posts/6581949/revisions "show revision history for this post") [Bite code](https://stackoverflow.com/users/9951)
Sign up to request clarification or add additional context in comments.
## 26 Comments
Add a comment
[](https://stackoverflow.com/users/4548304/max-goodridge)
Max Goodridge
[Max Goodridge](https://stackoverflow.com/users/4548304/max-goodridge)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment73803183_6581949)
It appears that in Django `models.Model` it does not use `__metaclass__` but rather `class Model(metaclass=ModelBase):` to reference a `ModelBase` class which then does the aforementioned metaclass magic. Great post! Here's the Django source: [github.com/django/django/blob/master/django/db/models/…](https://github.com/django/django/blob/master/django/db/models/base.py#L382)
2017-04-12T13:18:59.03Z+00:00
80
Reply
- Copy link
[](https://stackoverflow.com/users/1861627/petrux)
petrux
[petrux](https://stackoverflow.com/users/1861627/petrux)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment74291770_6581949)
\<\<Be careful here that the `__metaclass__` attribute will not be inherited, the metaclass of the parent (`Bar.__class__`) will be. If `Bar` used a `__metaclass__` attribute that created `Bar` with `type()` (and not `type.__new__()`), the subclasses will not inherit that behavior.\>\> -- Could you/someone please explain a bit deeper this passage?
2017-04-25T21:32:44.183Z+00:00
40
Reply
- Copy link
[](https://stackoverflow.com/users/166389/tbble)
TBBle
[TBBle](https://stackoverflow.com/users/166389/tbble)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment76037462_6581949)
@MaxGoodridge That's the Python 3 syntax for metaclasses. See [Python 3.6 Data model](https://docs.python.org/3.6/reference/datamodel.html#metaclasses) VS [Python 2.7 Data model](https://docs.python.org/2.7/reference/datamodel.html#customizing-class-creation)
2017-06-13T13:22:27.717Z+00:00
37
Reply
- Copy link
[](https://stackoverflow.com/users/281545/mr-and-mrs-d)
Mr\_and\_Mrs\_D
[Mr\_and\_Mrs\_D](https://stackoverflow.com/users/281545/mr-and-mrs-d)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment79928729_6581949)
`Now you wonder why the heck is it written in lowercase, and not Type?` - well because it's implemented in C - it's the same reason defaultdict is lowercase while OrderedDict (in python 2) is normal CamelCase
2017-09-29T10:47:27.31Z+00:00
32
Reply
- Copy link
[](https://stackoverflow.com/users/2962794/br%C5%8Dtsyorfuzthr%C4%81x)
Brōtsyorfuzthrāx
[Brōtsyorfuzthrāx](https://stackoverflow.com/users/2962794/br%C5%8Dtsyorfuzthr%C4%81x)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment81299800_6581949)
It's a community wiki answer (so, those who commented with corrections/improvements might consider editing their comments into the answer, if they're sure they are correct).
2017-11-08T08:59:31.923Z+00:00
35
Reply
- Copy link
Add a comment
\|
Show 21 more comments
This answer is useful
3442
Save this answer.
Show activity on this post.
A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.
While in Python you can use arbitrary callables for metaclasses (like [Jerub](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/100037#100037) shows), the better approach is to make it an actual class itself. `type` is the usual metaclass in Python. `type` is itself a class, and it is its own type. You won't be able to recreate something like `type` purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass `type`.
A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the normal `__init__` and `__new__` methods, metaclasses therefore allow you to do 'extra things' when creating a class, like registering the new class with some registry or replace the class with something else entirely.
When the `class` statement is executed, Python first executes the body of the `class` statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the `__metaclass__` attribute of the class-to-be (if any) or the `__metaclass__` global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.
However, metaclasses actually define the *type* of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass. These metaclass-methods are like classmethods in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. `type.__subclasses__()` is an example of a method on the `type` metaclass. You can also define the normal 'magic' methods, like `__add__`, `__iter__` and `__getattr__`, to implement or change how the class behaves.
Here's an aggregated example of the bits and pieces:
```
Copy
```
[Share](https://stackoverflow.com/a/100146 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/100146/edit)
Follow
Follow this answer to receive notifications
[edited Mar 4, 2019 at 21:34](https://stackoverflow.com/posts/100146/revisions "show all edits to this post")
[](https://stackoverflow.com/users/11150495/cameron-savage)
[Cameron Savage](https://stackoverflow.com/users/11150495/cameron-savage)
722 bronze badges
answered Sep 19, 2008 at 7:01
[](https://stackoverflow.com/users/17624/thomas-wouters)
[Thomas Wouters](https://stackoverflow.com/users/17624/thomas-wouters)
134k2323 gold badges153153 silver badges123123 bronze badges
## 10 Comments
Add a comment
[](https://stackoverflow.com/users/3750257/perry)
Perry
[Perry](https://stackoverflow.com/users/3750257/perry)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment77935564_100146)
`class A(type):pass<NEWLINE>class B(type,metaclass=A):pass<NEWLINE>b.__class__ = b`
2017-08-03T14:34:29.263Z+00:00
20
Reply
- Copy link
[](https://stackoverflow.com/users/7513138/holle-van)
Holle van
[Holle van](https://stackoverflow.com/users/7513138/holle-van)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment91736655_100146)
ppperry he obviously meant you can't recreate type without using type itself as a metaclass. Which is fair enough to say.
2018-09-18T23:24:10.793Z+00:00
38
Reply
- Copy link
[](https://stackoverflow.com/users/3311276/ciasto-piekarz)
Ciasto piekarz
[Ciasto piekarz](https://stackoverflow.com/users/3311276/ciasto-piekarz)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment93929134_100146)
Shouldn't unregister() be called by instance of Example class ?
2018-11-29T00:59:15Z+00:00
7
Reply
- Copy link
[](https://stackoverflow.com/users/2097/blackshift)
BlackShift
[BlackShift](https://stackoverflow.com/users/2097/blackshift)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment98519860_100146)
Note that `__metaclass__` is not supported in Python 3. In Python 3 use `class MyObject(metaclass=MyType)`, see [python.org/dev/peps/pep-3115](https://www.python.org/dev/peps/pep-3115/) and the answer below.
2019-05-01T08:36:00.933Z+00:00
23
Reply
- Copy link
[](https://stackoverflow.com/users/1126841/chepner)
chepner
[chepner](https://stackoverflow.com/users/1126841/chepner)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment105503046_100146)
The documentation describes [how the metaclass is chosen](https://docs.python.org/3/reference/datamodel.html#determining-the-appropriate-metaclass). The metaclass isn't inherited so much as it is derived. If you specify a metaclass, it has to be a subtype of each base class metaclass; otherwise, you'll use the a base class metaclass that is a subtype of each other base class metaclass. Note that it is possible that *no* valid metaclass can be found, and the definition will fail.
2020-01-09T21:14:22.89Z+00:00
7
Reply
- Copy link
Add a comment
\|
Show 5 more comments
This answer is useful
494
Save this answer.
Show activity on this post.
*Note, this answer is for Python 2.x as it was written in 2008, metaclasses are slightly different in 3.x.*
Metaclasses are the secret sauce that make 'class' work. The default metaclass for a new style object is called 'type'.
```
class type(object)
| type(object) -> the object's type
| type(name, bases, dict) -> a new type
```
Metaclasses take 3 args. '**name**', '**bases**' and '**dict**'
Here is where the secret starts. Look for where name, bases and the dict come from in this example class definition.
```
Copy
```
Lets define a metaclass that will demonstrate how '**class:**' calls it.
```
Copy
```
And now, an example that actually means something, this will automatically make the variables in the list "attributes" set on the class, and set to None.
```
Copy
```
**Note that the magic behaviour that `Initialised` gains by having the metaclass `init_attributes` is not passed onto a subclass of `Initialised`.**
Here is an even more concrete example, showing how you can subclass 'type' to make a metaclass that performs an action when the class is created. This is quite tricky:
```
Copy
```
[Share](https://stackoverflow.com/a/100037 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/100037/edit)
Follow
Follow this answer to receive notifications
[edited Nov 6, 2019 at 7:57](https://stackoverflow.com/posts/100037/revisions "show all edits to this post")
[](https://stackoverflow.com/users/5169236/ralh)
[ralh](https://stackoverflow.com/users/5169236/ralh)
2,59411 gold badge1616 silver badges1919 bronze badges
answered Sep 19, 2008 at 6:26
[](https://stackoverflow.com/users/14648/jerub)
[Jerub](https://stackoverflow.com/users/14648/jerub)
42\.8k1515 gold badges7676 silver badges9191 bronze badges
## Comments
Add a comment
This answer is useful
237
Save this answer.
Show activity on this post.
Others have explained how metaclasses work and how they fit into the Python type system. Here's an example of what they can be used for. In a testing framework I wrote, I wanted to keep track of the order in which classes were defined, so that I could later instantiate them in this order. I found it easiest to do this using a metaclass.
```
Copy
```
Anything that's a subclass of `MyType` then gets a class attribute `_order` that records the order in which the classes were defined.
[Share](https://stackoverflow.com/a/6428779 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/6428779/edit)
Follow
Follow this answer to receive notifications
[edited Nov 28, 2016 at 18:04](https://stackoverflow.com/posts/6428779/revisions "show all edits to this post")
answered Jun 21, 2011 at 16:30
[](https://stackoverflow.com/users/416467/kindall)
[kindall](https://stackoverflow.com/users/416467/kindall)
185k3636 gold badges291291 silver badges321321 bronze badges
## 5 Comments
Add a comment
[](https://stackoverflow.com/users/4105/michael-gundlach)
Michael Gundlach
[Michael Gundlach](https://stackoverflow.com/users/4105/michael-gundlach)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment98108709_6428779)
Thanks for the example. Why did you find this easier than inheriting from MyBase, whose `__init__(self)` says `type(self)._order = MyBase.counter; MyBase.counter += 1` ?
2019-04-16T17:59:34.573Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/416467/kindall)
kindall
[kindall](https://stackoverflow.com/users/416467/kindall)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment98108978_6428779)
I wanted the classes themselves, not their instances, to be numbered.
2019-04-16T18:09:39.633Z+00:00
7
Reply
- Copy link
[](https://stackoverflow.com/users/4105/michael-gundlach)
Michael Gundlach
[Michael Gundlach](https://stackoverflow.com/users/4105/michael-gundlach)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment98151100_6428779)
Right, duh. Thanks. My code would reset MyType's attribute on every instantiation, and would never set the attribute if an instance of MyType was never created. Oops. (And a class property could also work, but unlike the metaclass it offers no obvious place to store the counter.)
2019-04-17T21:58:00.003Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/595305/mike-rodent)
mike rodent
[mike rodent](https://stackoverflow.com/users/595305/mike-rodent)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment103320847_6428779)
This is a jolly interesting example, not least because one can genuinely see why a metaclass could be neeeded with this, to supply a solution to a specific difficulty. OTOH I struggle to be convinced that anyone would really need to instantiate objects in the order in which their classes were defined: I guess we just have to take your word for that :).
2019-10-22T00:09:43.853Z+00:00
1
Reply
- Copy link
[](https://stackoverflow.com/users/416467/kindall)
kindall
[kindall](https://stackoverflow.com/users/416467/kindall)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment119148264_6428779)
It was a documentation testing framework and the classes were declarative descriptions of the specific files to be tested, tests to be run, and so forth. The framework reported the results of these in a nicely formatted report grouped by product, document, and test. The report was more useful if it the tests were run in a predictable order. :-)
2021-05-05T20:57:31.943Z+00:00
3
Reply
- Copy link
Add a comment
This answer is useful
201
Save this answer.
Show activity on this post.
One use for metaclasses is adding new properties and methods to an instance automatically.
For example, if you look at [Django models](http://docs.djangoproject.com/en/dev/topics/db/models/), their definition looks a bit confusing. It looks as if you are only defining class properties:
```
Copy
```
However, at runtime the Person objects are filled with all sorts of useful methods. See the [source](http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py) for some amazing metaclassery.
[Share](https://stackoverflow.com/a/100091 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 2.5](https://creativecommons.org/licenses/by-sa/2.5/ "The current license for this post: CC BY-SA 2.5")
[Improve this answer](https://stackoverflow.com/posts/100091/edit)
Follow
Follow this answer to receive notifications
answered Sep 19, 2008 at 6:45
[](https://stackoverflow.com/users/8570/antti-rasinen)
[Antti Rasinen](https://stackoverflow.com/users/8570/antti-rasinen)
10\.2k22 gold badges2525 silver badges1818 bronze badges
## 1 Comment
Add a comment
[](https://stackoverflow.com/users/5005177/trixn)
trixn
[trixn](https://stackoverflow.com/users/5005177/trixn)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment70991701_100091)
Isn't the use of meta classes adding new properties and methods to a **class** and not an instance? As far as i understood it the meta class alters the class itself and as a result the instances can be constructed differently by the altered class. Could be a bit misleading to people who try to get the nature of a meta class. Having useful methods on instances can be achieved by normal inherence. The reference to Django code as an example is good, though.
2017-01-27T23:24:42.163Z+00:00
15
Reply
- Copy link
This answer is useful
165
Save this answer.
Show activity on this post.
I think the ONLamp introduction to metaclass programming is well written and gives a really good introduction to the topic despite being several years old already.
<http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html> (archived at <https://web.archive.org/web/20080206005253/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html>)
In short: A class is a blueprint for the creation of an instance, a metaclass is a blueprint for the creation of a class. It can be easily seen that in Python classes need to be first-class objects too to enable this behavior.
I've never written one myself, but I think one of the nicest uses of metaclasses can be seen in the [Django framework](http://www.djangoproject.com/). The model classes use a metaclass approach to enable a declarative style of writing new models or form classes. While the metaclass is creating the class, all members get the possibility to customize the class itself.
- [Creating a new model](http://docs.djangoproject.com/en/dev/intro/tutorial01/#id3)
- [The metaclass enabling this](http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py#L25)
The thing that's left to say is: If you don't know what metaclasses are, the probability that you **will not need them** is 99%.
[Share](https://stackoverflow.com/a/100059 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/100059/edit)
Follow
Follow this answer to receive notifications
[edited Aug 13, 2018 at 4:53](https://stackoverflow.com/posts/100059/revisions "show all edits to this post")
[](https://stackoverflow.com/users/2350164/yet-another-user)
[Yet Another User](https://stackoverflow.com/users/2350164/yet-another-user)
2,96533 gold badges2121 silver badges2828 bronze badges
answered Sep 19, 2008 at 6:32
[](https://stackoverflow.com/users/317346/matthias-kestenholz)
[Matthias Kestenholz](https://stackoverflow.com/users/317346/matthias-kestenholz)
3,36811 gold badge2323 silver badges2626 bronze badges
## Comments
Add a comment
This answer is useful
151
Save this answer.
Show activity on this post.
> ## What are metaclasses? What do you use them for?
TLDR: A metaclass instantiates and defines behavior for a class just like a class instantiates and defines behavior for an instance.
Pseudocode:
```
Copy
```
The above should look familiar. Well, where does `Class` come from? It's an instance of a metaclass (also pseudocode):
```
Copy
```
In real code, we can pass the default metaclass, `type`, everything we need to instantiate a class and we get a class:
```
Copy
```
## Putting it differently
- A class is to an instance as a metaclass is to a class.
When we instantiate an object, we get an instance:
```
Copy
```
Likewise, when we define a class explicitly with the default metaclass, `type`, we instantiate it:
```
Copy
```
- Put another way, a class is an instance of a metaclass:
```
Copy
```
- Put a third way, a metaclass is a class's class.
```
Copy
```
When you write a class definition and Python executes it, it uses a metaclass to instantiate the class object (which will, in turn, be used to instantiate instances of that class).
Just as we can use class definitions to change how custom object instances behave, we can use a metaclass class definition to change the way a class object behaves.
What can they be used for? From the [docs](https://docs.python.org/3/reference/datamodel.html#metaclass-example):
> The potential uses for metaclasses are boundless. Some ideas that have been explored include logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.
Nevertheless, it is usually encouraged for users to avoid using metaclasses unless absolutely necessary.
# You use a metaclass every time you create a class:
When you write a class definition, for example, like this,
```
Copy
```
You instantiate a class object.
```
Copy
```
It is the same as functionally calling `type` with the appropriate arguments and assigning the result to a variable of that name:
```
Copy
```
Note, some things automatically get added to the `__dict__`, i.e., the namespace:
```
Copy
```
The *metaclass* of the object we created, in both cases, is `type`.
(A side-note on the contents of the class `__dict__`: `__module__` is there because classes must know where they are defined, and `__dict__` and `__weakref__` are there because we don't define `__slots__` - if we [define `__slots__`](https://stackoverflow.com/q/472000/541136) we'll save a bit of space in the instances, as we can disallow `__dict__` and `__weakref__` by excluding them. For example:
```
Copy
```
... but I digress.)
# We can extend `type` just like any other class definition:
Here's the default `__repr__` of classes:
```
Copy
```
One of the most valuable things we can do by default in writing a Python object is to provide it with a good `__repr__`. When we call `help(repr)` we learn that there's a good test for a `__repr__` that also requires a test for equality - `obj == eval(repr(obj))`. The following simple implementation of `__repr__` and `__eq__` for class instances of our type class provides us with a demonstration that may improve on the default `__repr__` of classes:
```
Copy
```
So now when we create an object with this metaclass, the `__repr__` echoed on the command line provides a much less ugly sight than the default:
```
Copy
```
With a nice `__repr__` defined for the class instance, we have a stronger ability to debug our code. However, much further checking with `eval(repr(Class))` is unlikely (as functions would be rather impossible to eval from their default `__repr__`'s).
# An expected usage: `__prepare__` a namespace
If, for example, we want to know in what order a class's methods are created in, we could provide an ordered dict as the namespace of the class. We would do this with `__prepare__` which [returns the namespace dict for the class if it is implemented in Python 3](https://docs.python.org/3/reference/datamodel.html#preparing-the-class-namespace):
```
Copy
```
And usage:
```
Copy
```
And now we have a record of the order in which these methods (and other class attributes) were created:
```
Copy
```
Note, this example was adapted from the [documentation](https://docs.python.org/3/reference/datamodel.html#metaclass-example) - the new [enum in the standard library](https://github.com/python/cpython/blob/master/Lib/enum.py) does this.
So what we did was instantiate a metaclass by creating a class. We can also treat the metaclass as we would any other class. It has a method resolution order:
```
Copy
```
And it has approximately the correct `repr` (which we can no longer eval unless we can find a way to represent our functions.):
```
Copy
```
[Share](https://stackoverflow.com/a/31930795 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/31930795/edit)
Follow
Follow this answer to receive notifications
[edited Aug 30, 2017 at 3:19](https://stackoverflow.com/posts/31930795/revisions "show all edits to this post")
answered Aug 10, 2015 at 23:28
[](https://stackoverflow.com/users/541136/aaron-hall)
[Aaron Hall](https://stackoverflow.com/users/541136/aaron-hall)♦
400k9393 gold badges417417 silver badges342342 bronze badges
## Comments
Add a comment
This answer is useful
113
Save this answer.
Show activity on this post.
**Python 3 update**
There are (at this point) two key methods in a metaclass:
- `__prepare__`, and
- `__new__`
`__prepare__` lets you supply a custom mapping (such as an `OrderedDict`) to be used as the namespace while the class is being created. You must return an instance of whatever namespace you choose. If you don't implement `__prepare__` a normal `dict` is used.
`__new__` is responsible for the actual creation/modification of the final class.
A bare-bones, do-nothing-extra metaclass would like:
```
Copy
```
A simple example:
Say you want some simple validation code to run on your attributes -- like it must always be an `int` or a `str`. Without a metaclass, your class would look something like:
```
Copy
```
As you can see, you have to repeat the name of the attribute twice. This makes typos possible along with irritating bugs.
A simple metaclass can address that problem:
```
Copy
```
This is what the metaclass would look like (not using `__prepare__` since it is not needed):
```
Copy
```
A sample run of:
```
Copy
```
produces:
```
Copy
```
***
**Note**: This example is simple enough it could have also been accomplished with a class decorator, but presumably an actual metaclass would be doing much more.
The 'ValidateType' class for reference:
```
Copy
```
[Share](https://stackoverflow.com/a/35732111 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/35732111/edit)
Follow
Follow this answer to receive notifications
answered Mar 1, 2016 at 19:48
[](https://stackoverflow.com/users/208880/ethan-furman)
[Ethan Furman](https://stackoverflow.com/users/208880/ethan-furman)
70\.2k2121 gold badges174174 silver badges251251 bronze badges
## 1 Comment
Add a comment
[](https://stackoverflow.com/users/1023470/lars)
Lars
[Lars](https://stackoverflow.com/users/1023470/lars)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment107036974_35732111)
Note that since python 3.6, you can use `__set_name__(cls, name)` in the descriptor (`ValidateType`) to set the name in the descriptor (`self.name` and in this case also `self.attr`). This was added to not have to dive into metaclasses for this specific common use case (see PEP 487).
2020-03-03T09:56:33.66Z+00:00
3
Reply
- Copy link
This answer is useful
105
Save this answer.
Show activity on this post.
# Role of a metaclass' `__call__()` method when creating a class instance
If you've done Python programming for more than a few months you'll eventually stumble upon code that looks like this:
```
Copy
```
The latter is possible when you implement the `__call__()` magic method on the class.
```
Copy
```
The `__call__()` method is invoked when an instance of a class is used as a callable. But as we've seen from previous answers a class itself is an instance of a metaclass, so when we use the class as a callable (i.e. when we create an instance of it) we're actually calling its metaclass' `__call__()` method. At this point most Python programmers are a bit confused because they've been told that when creating an instance like this `instance = SomeClass()` you're calling its `__init__()` method. Some who've dug a bit deeper know that before `__init__()` there's `__new__()`. Well, today another layer of truth is being revealed, before `__new__()` there's the metaclass' `__call__()`.
Let's study the method call chain from specifically the perspective of creating an instance of a class.
This is a metaclass that logs exactly the moment before an instance is created and the moment it's about to return it.
```
Copy
```
This is a class that uses that metaclass
```
Copy
```
And now let's create an instance of `Class_1`
```
Copy
```
Observe that the code above doesn't actually do anything more than logging the tasks. Each method delegates the actual work to its parent's implementation, thus keeping the default behavior. Since `type` is `Meta_1`'s parent class (`type` being the default parent metaclass) and considering the ordering sequence of the output above, we now have a clue as to what would be the pseudo implementation of `type.__call__()`:
```
Copy
```
We can see that the metaclass' `__call__()` method is the one that's called first. It then delegates creation of the instance to the class's `__new__()` method and initialization to the instance's `__init__()`. It's also the one that ultimately returns the instance.
From the above it stems that the metaclass' `__call__()` is also given the opportunity to decide whether or not a call to `Class_1.__new__()` or `Class_1.__init__()` will eventually be made. Over the course of its execution it could actually return an object that hasn't been touched by either of these methods. Take for example this approach to the singleton pattern:
```
Copy
```
Let's observe what happens when repeatedly trying to create an object of type `Class_2`
```
Copy
```
[Share](https://stackoverflow.com/a/40017019 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/40017019/edit)
Follow
Follow this answer to receive notifications
[edited Aug 27, 2018 at 17:21](https://stackoverflow.com/posts/40017019/revisions "show all edits to this post")
answered Oct 13, 2016 at 9:21
[](https://stackoverflow.com/users/56974/michael-ekoka)
[Michael Ekoka](https://stackoverflow.com/users/56974/michael-ekoka)
20\.3k1212 gold badges8383 silver badges8383 bronze badges
## 1 Comment
Add a comment
[](https://stackoverflow.com/users/3412660/rich-lysakowski-phd)
Rich Lysakowski PhD
[Rich Lysakowski PhD](https://stackoverflow.com/users/3412660/rich-lysakowski-phd)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment104328842_40017019)
This is a good addition to the previously upvoted "accepted answer". It provides examples for intermediate coders to chew on.
2019-11-26T03:51:05.947Z+00:00
3
Reply
- Copy link
This answer is useful
78
Save this answer.
Show activity on this post.
A `metaclass` is a class that tells how (some) other class should be created.
This is a case where I saw `metaclass` as a solution to my problem: I had a really complicated problem, that probably could have been solved differently, but I chose to solve it using a `metaclass`. Because of the complexity, it is one of the few modules I have written where the comments in the module surpass the amount of code that has been written. Here it is...
```
Copy
```
[Share](https://stackoverflow.com/a/21999253 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/21999253/edit)
Follow
Follow this answer to receive notifications
[edited Apr 1, 2022 at 19:47](https://stackoverflow.com/posts/21999253/revisions "show all edits to this post")
community wiki
[4 revs, 3 users 69%](https://stackoverflow.com/posts/21999253/revisions "show revision history for this post") [Craig](https://stackoverflow.com/users/1489354)
## 1 Comment
Add a comment
user9710374
user9710374
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment126889979_21999253)
pylint says your code has been rated at -1.03/10.
2022-04-09T00:15:47.95Z+00:00
3
Reply
- Copy link
This answer is useful
65
Save this answer.
Show activity on this post.
## The tl;dr version
The `type(obj)` function gets you the type of an object.
**The `type()` of a class is its *metaclass*.**
To use a metaclass:
```
Copy
```
`type` is its own metaclass. The class of a class is a metaclass-- the body of a class is the arguments passed to the metaclass that is used to construct the class.
[Here](https://docs.python.org/3/reference/datamodel.html#metaclasses) you can read about how to use metaclasses to customize class construction.
[Share](https://stackoverflow.com/a/41338238 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/41338238/edit)
Follow
Follow this answer to receive notifications
[edited Dec 5, 2019 at 16:27](https://stackoverflow.com/posts/41338238/revisions "show all edits to this post")
answered Dec 27, 2016 at 2:21
[](https://stackoverflow.com/users/1459669/no%C9%A5%CA%87%CA%8E%D4%80%CA%8Ez%C9%90%C9%B9%C6%86)
[noɥʇʎԀʎzɐɹƆ](https://stackoverflow.com/users/1459669/no%C9%A5%CA%87%CA%8E%D4%80%CA%8Ez%C9%90%C9%B9%C6%86)
10\.8k33 gold badges5252 silver badges6767 bronze badges
## Comments
Add a comment
This answer is useful
60
Save this answer.
Show activity on this post.
`type` is actually a `metaclass` -- a class that creates another classes. Most `metaclass` are the subclasses of `type`. The `metaclass` receives the `new` class as its first argument and provide access to class object with details as mentioned below:
```
Copy
```
`Note:`
Notice that the class was not instantiated at any time; the simple act of creating the class triggered execution of the `metaclass`.
[Share](https://stackoverflow.com/a/38858285 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/38858285/edit)
Follow
Follow this answer to receive notifications
[edited Aug 29, 2017 at 5:23](https://stackoverflow.com/posts/38858285/revisions "show all edits to this post")
[](https://stackoverflow.com/users/257635/chankey-pathak)
[Chankey Pathak](https://stackoverflow.com/users/257635/chankey-pathak)
21\.8k1212 gold badges8888 silver badges138138 bronze badges
answered Aug 9, 2016 at 18:49
[](https://stackoverflow.com/users/4636600/mushahid-khan)
[Mushahid Khan](https://stackoverflow.com/users/4636600/mushahid-khan)
2,84411 gold badge2121 silver badges3232 bronze badges
## Comments
Add a comment
This answer is useful
43
Save this answer.
Show activity on this post.
Python classes are themselves objects - as in instance - of their meta-class.
The default metaclass, which is applied when when you determine classes as:
```
Copy
```
meta class are used to apply some rule to an entire set of classes. For example, suppose you're building an ORM to access a database, and you want records from each table to be of a class mapped to that table (based on fields, business rules, etc..,), a possible use of metaclass is for instance, connection pool logic, which is share by all classes of record from all tables. Another use is logic to to support foreign keys, which involves multiple classes of records.
when you define metaclass, you subclass type, and can overrided the following magic methods to insert your logic.
```
Copy
```
anyhow, those two are the most commonly used hooks. metaclassing is powerful, and above is nowhere near and exhaustive list of uses for metaclassing.
[Share](https://stackoverflow.com/a/45074712 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/45074712/edit)
Follow
Follow this answer to receive notifications
[edited Jul 13, 2017 at 8:18](https://stackoverflow.com/posts/45074712/revisions "show all edits to this post")
answered Jul 13, 2017 at 7:58
[](https://stackoverflow.com/users/8056974/xingzhou-liu)
[Xingzhou Liu](https://stackoverflow.com/users/8056974/xingzhou-liu)
1,57999 silver badges1313 bronze badges
## Comments
Add a comment
This answer is useful
41
Save this answer.
Show activity on this post.
The type() function can return the type of an object or create a new type,
for example, we can create a Hi class with the type() function and do not need to use this way with class Hi(object):
```
Copy
```
In addition to using type() to create classes dynamically, you can control creation behavior of class and use metaclass.
According to the Python object model, the class is the object, so the class must be an instance of another certain class. By default, a Python class is instance of the type class. That is, type is metaclass of most of the built-in classes and metaclass of user-defined classes.
```
Copy
```
Magic will take effect when we passed keyword arguments in metaclass, it indicates the Python interpreter to create the CustomList through ListMetaclass. **new** (), at this point, we can modify the class definition, for example, and add a new method and then return the revised definition.
[Share](https://stackoverflow.com/a/48222963 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/48222963/edit)
Follow
Follow this answer to receive notifications
[edited Jan 12, 2018 at 9:30](https://stackoverflow.com/posts/48222963/revisions "show all edits to this post")
answered Jan 12, 2018 at 9:16
[](https://stackoverflow.com/users/5064780/binbjz)
[binbjz](https://stackoverflow.com/users/5064780/binbjz)
88111 gold badge1111 silver badges1515 bronze badges
## Comments
Add a comment
This answer is useful
30
Save this answer.
Show activity on this post.
In addition to the published answers I can say that a `metaclass` defines the behaviour for a class. So, you can explicitly set your metaclass. Whenever Python gets a keyword `class` then it starts searching for the `metaclass`. If it's not found – the default metaclass type is used to create the class's object. Using the `__metaclass__` attribute, you can set `metaclass` of your class:
```
Copy
```
It'll produce the output like this:
```
Copyclass 'type'
```
And, of course, you can create your own `metaclass` to define the behaviour of any class that are created using your class.
For doing that, your default `metaclass` type class must be inherited as this is the main `metaclass`:
```
Copy
```
The output will be:
```
Copy
```
[Share](https://stackoverflow.com/a/52344780 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/52344780/edit)
Follow
Follow this answer to receive notifications
[edited Sep 15, 2018 at 13:17](https://stackoverflow.com/posts/52344780/revisions "show all edits to this post")
answered Sep 15, 2018 at 12:41
[](https://stackoverflow.com/users/6599590/andy-jazz)
[Andy Jazz](https://stackoverflow.com/users/6599590/andy-jazz)
61k1919 gold badges166166 silver badges263263 bronze badges
## Comments
Add a comment
This answer is useful
22
Save this answer.
Show activity on this post.
Note that in python 3.6 a new dunder method `__init_subclass__(cls, **kwargs)` was introduced to replace a lot of common use cases for metaclasses. Is is called when a subclass of the defining class is created. See [python docs](https://docs.python.org/3.6/reference/datamodel.html).
[Share](https://stackoverflow.com/a/60504738 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/60504738/edit)
Follow
Follow this answer to receive notifications
answered Mar 3, 2020 at 10:06
[](https://stackoverflow.com/users/1023470/lars)
[Lars](https://stackoverflow.com/users/1023470/lars)
2,01922 gold badges1616 silver badges2626 bronze badges
## Comments
Add a comment
This answer is useful
20
Save this answer.
Show activity on this post.
Here's another example of what it can be used for:
- You can use the `metaclass` to change the function of its instance (the class).
```
Copy
```
The `metaclass` is powerful, there are many things (such as monkey magic) you can do with it, but be careful this may only be known to you.
[Share](https://stackoverflow.com/a/59424178 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/59424178/edit)
Follow
Follow this answer to receive notifications
answered Dec 20, 2019 at 11:03
[](https://stackoverflow.com/users/9935654/carson)
[Carson](https://stackoverflow.com/users/9935654/carson)
8,96822 gold badges6262 silver badges6262 bronze badges
## Comments
Add a comment
This answer is useful
18
Save this answer.
Show activity on this post.
**The top answer is correct**.
But readers may be coming here searching answers about similarly named inner classes. They are present in popular libraries, such as `Django` and `WTForms`.
As DavidW points out in the comments beneath this answer, **these are *library-specific* features and are not to be confused with the advanced, unrelated *Python language* feature with a similar name**.
Rather, these are namespaces within classes' dicts. They are constructed using inner classes for sake of readability.
In this example special field, `abstract` is visibly separate from fields of Author model.
```
Copy
```
Another example is from the documentation for `WTForms`:
```
Copy
```
This syntax does not get special treatment in the python programming language. `Meta` is not a keyword here, and does not trigger metaclass behavior. Rather, third-party library code in packages like `Django` and `WTForms` reads this property in the constructors of certain classes, and elsewhere.
The presence of these declarations modifies the behavior of the classes that have these declarations. For example, `WTForms` reads `self.Meta.csrf` to determine if the form needs a `csrf` field.
[Share](https://stackoverflow.com/a/68417609 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/68417609/edit)
Follow
Follow this answer to receive notifications
[edited Sep 21, 2021 at 11:49](https://stackoverflow.com/posts/68417609/revisions "show all edits to this post")
[](https://stackoverflow.com/users/13990016/alex-waygood)
[Alex Waygood](https://stackoverflow.com/users/13990016/alex-waygood)
7,80733 gold badges3131 silver badges5050 bronze badges
answered Jul 17, 2021 at 5:18
[](https://stackoverflow.com/users/14964700/manukumar)
[Manukumar](https://stackoverflow.com/users/14964700/manukumar)
22522 silver badges44 bronze badges
## 4 Comments
Add a comment
[](https://stackoverflow.com/users/4657412/davidw)
DavidW
[DavidW](https://stackoverflow.com/users/4657412/davidw)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment121895614_68417609)
This is a Django-specific feature where a nested class called `Meta` has a special meaning. The question is about an unrelated Python language feature with a similar name.
2021-08-29T10:40:21.713Z+00:00
2
Reply
- Copy link
[](https://stackoverflow.com/users/13990016/alex-waygood)
Alex Waygood
[Alex Waygood](https://stackoverflow.com/users/13990016/alex-waygood)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment122429868_68417609)
@DavidW — hamilyon undertook a heroic edit of this post. It's now, in my opinion, quite a useful answer.
2021-09-21T11:53:37.64Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/4657412/davidw)
DavidW
[DavidW](https://stackoverflow.com/users/4657412/davidw)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment122439128_68417609)
@AlexWaygood I'd probably have rejected the edit (too big a change...) but I can see that it does clarify something that's a point of confusion so it probably is useful. With that in mind, I've removed my downvote.
2021-09-21T17:52:51.4Z+00:00
1
Reply
- Copy link
[](https://stackoverflow.com/users/13990016/alex-waygood)
Alex Waygood
[Alex Waygood](https://stackoverflow.com/users/13990016/alex-waygood)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment122440234_68417609)
@DavidW yeah, I think you could argue it both ways. I wouldn't normally approve an edit that large. But I felt like it kept to the spirit of the original post, and it seemed like a fair amount of work had gone into a noble endeavour (clarifying a legitimate point of confusion), so decided to approve.
2021-09-21T18:45:07.483Z+00:00
0
Reply
- Copy link
Add a comment
This answer is useful
17
Save this answer.
Show activity on this post.
In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain class and their instances The term metaclass simply means something used to create classes. In other words, it is the class of a class. The metaclass is used to create the class so like the object being an instance of a class, a class is an instance of a metaclass. In python classes are also considered objects.
[Share](https://stackoverflow.com/a/56945952 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/56945952/edit)
Follow
Follow this answer to receive notifications
[edited Jul 9, 2019 at 5:45](https://stackoverflow.com/posts/56945952/revisions "show all edits to this post")
answered Jul 9, 2019 at 5:37
[](https://stackoverflow.com/users/1609259/venu-gopal-tewari)
[Venu Gopal Tewari](https://stackoverflow.com/users/1609259/venu-gopal-tewari)
5,9164545 silver badges4141 bronze badges
## 2 Comments
Add a comment
[](https://stackoverflow.com/users/608170/verisimilitude)
verisimilitude
[verisimilitude](https://stackoverflow.com/users/608170/verisimilitude)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment100573238_56945952)
Rather than giving bookish definitions, would have been better if you had added some examples. The first line of your answer seems to have been copied from the Wikipedia entry of Metaclasses.
2019-07-13T17:41:52.803Z+00:00
6
Reply
- Copy link
[](https://stackoverflow.com/users/1609259/venu-gopal-tewari)
Venu Gopal Tewari
[Venu Gopal Tewari](https://stackoverflow.com/users/1609259/venu-gopal-tewari)
[Over a year ago](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#comment100596443_56945952)
@verisimilitude I am also learning can you help me improving this answer by providing some practical examples from your experience ??
2019-07-15T06:02:13.647Z+00:00
3
Reply
- Copy link
This answer is useful
17
Save this answer.
Show activity on this post.
A class, in Python, is an object, and just like any other object, it is an instance of "something". This "something" is what is termed as a Metaclass. This metaclass is a special type of class that creates other class's objects. Hence, metaclass is responsible for making new classes. This allows the programmer to customize the way classes are generated.
To create a metaclass, overriding of **new**() and **init**() methods is usually done. **new**() can be overridden to change the way objects are created, while **init**() can be overridden to change the way of initializing the object. Metaclass can be created by a number of ways. One of the ways is to use type() function. type() function, when called with 3 parameters, creates a metaclass. The parameters are :-
1. Class Name
2. Tuple having base classes inherited by class
3. A dictionary having all class methods and class variables
Another way of creating a metaclass comprises of 'metaclass' keyword. Define the metaclass as a simple class. In the parameters of inherited class, pass metaclass=metaclass\_name
Metaclass can be specifically used in the following situations :-
1. when a particular effect has to be applied to all the subclasses
2. Automatic change of class (on creation) is required
3. By API developers
[Share](https://stackoverflow.com/a/59818321 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/59818321/edit)
Follow
Follow this answer to receive notifications
answered Jan 20, 2020 at 6:59
[](https://stackoverflow.com/users/9851541/swati-srivastava)
[Swati Srivastava](https://stackoverflow.com/users/9851541/swati-srivastava)
1,20711 gold badge1414 silver badges2020 bronze badges
## Comments
Add a comment
This answer is useful
12
Save this answer.
Show activity on this post.
I saw an interesting use case for metaclasses in a package called `classutilities`. It checks if all class variables are in upper case format (it is convenient to have unified logic for configuration classes), and checks if there are no instance level methods in class. Another interesting example for metaclases was deactivation of unittests based on complex conditions (checking values of multiple environmental variables).
[Share](https://stackoverflow.com/a/68354618 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/68354618/edit)
Follow
Follow this answer to receive notifications
[edited Jul 12, 2021 at 22:53](https://stackoverflow.com/posts/68354618/revisions "show all edits to this post")
[](https://stackoverflow.com/users/16435061/arthur-macmillan)
[Arthur MacMillan](https://stackoverflow.com/users/16435061/arthur-macmillan)
10177 bronze badges
answered Jul 12, 2021 at 22:51
[](https://stackoverflow.com/users/13649935/emma-brown)
[Emma Brown](https://stackoverflow.com/users/13649935/emma-brown)
19511 silver badge88 bronze badges
## Comments
Add a comment
This answer is useful
11
Save this answer.
Show activity on this post.
In Python, a metaclass is a subclass of a subclass that determines how a subclass behaves. A class is an instance of another metaclass. In Python, a class specifies how the class's instance will behave.
Since metaclasses are in charge of class generation, you can write your own custom metaclasses to change how classes are created by performing additional actions or injecting code. Custom metaclasses aren't always important, but they can be.
[Share](https://stackoverflow.com/a/67201732 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/67201732/edit)
Follow
Follow this answer to receive notifications
answered Apr 21, 2021 at 18:41
[](https://stackoverflow.com/users/15691322/officialnebz)
[OfficialNebz](https://stackoverflow.com/users/15691322/officialnebz)
45555 silver badges1010 bronze badges
## Comments
Add a comment
This answer is useful
3
Save this answer.
Show activity on this post.
look this:
```
Copy
```
In other words, when an object was not created (type of object), we looking MetaClass.
[Share](https://stackoverflow.com/a/69426577 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/69426577/edit)
Follow
Follow this answer to receive notifications
answered Oct 3, 2021 at 16:06
[](https://stackoverflow.com/users/16608876/delta)
[Delta](https://stackoverflow.com/users/16608876/delta)
37011 silver badge1010 bronze badges
## Comments
Add a comment
This answer is useful
3
Save this answer.
Show activity on this post.
i want to add a little on why `type.__new__()` over `type()`
first, take a look at following classes
```
Copy
```
1. `type.__new__` just assigned `MyMeta` to `AClass.__class__`.
how? `type.__new__` would take the first parameter cls, which
is MyMeta, and execute `AClass.__class__ = MyMeta`.
when we tried to create SubAClass a subclass of AClass, Python would
take a look at the metaclass we designated to be used to create SubAClass
and in this case, we did not pass a metaclass for SubAClass, so Python got a None for metaclass.
then Python would try to pick up the metaclass of the first base class of SubAClass, apparently it got `MyMeta`.
2. if you called `type()` instead of `type.__new__`, then we
would have `AClass.__class__` to be `type`. why?
`type()` still calls `type.__new__` but passes `type` as the first parameter implicitly.
that means AClass would be equivalent of BClass, both of them have type
as their `__class__` attr
## how the searching of metaclass works in C code?
it works pretty much like what we've just mentioned
the function `builtin___build_class__` would be called when you defined a class
and code is just so straightforward
```
Copy
```
basically, `meta = (PyObject *)Py_TYPE(base0);` is everything we want to know
it can be translated to be `meta = Py_TYPE(AClass) = MyMeta = AClass.__class__`
[Share](https://stackoverflow.com/a/75418816 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/75418816/edit)
Follow
Follow this answer to receive notifications
[edited May 8, 2023 at 4:07](https://stackoverflow.com/posts/75418816/revisions "show all edits to this post")
answered Feb 11, 2023 at 7:55
[](https://stackoverflow.com/users/3197067/user3197067)
[user3197067](https://stackoverflow.com/users/3197067/user3197067)
4155 bronze badges
## Comments
Add a comment
This answer is useful
1
Save this answer.
Show activity on this post.
If you are familiar with meta-programing. you should known meta-programing is a kind of programing that controls programing.
In Python, metaclass is a way of meta-programing.
**You can use metaclass to create class.**
Follow rules:
- Metaclass is used to **create** class.
- Python build-in the metaclass. called ***type***
- You can customize own metaclass by inheriting ***type***
- By setting a class's metaclass, you can change its **default behavior**.
Code example:
```
Copy
```
output:
```
Copy
```
[Share](https://stackoverflow.com/a/78502029 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/78502029/edit)
Follow
Follow this answer to receive notifications
[edited Mar 23 at 12:25](https://stackoverflow.com/posts/78502029/revisions "show all edits to this post")
[](https://stackoverflow.com/users/734335/mathieu-rodic)
[Mathieu Rodic](https://stackoverflow.com/users/734335/mathieu-rodic)
6,77022 gold badges4545 silver badges4949 bronze badges
answered May 19, 2024 at 8:45
[](https://stackoverflow.com/users/14268186/hupo)
[hupo](https://stackoverflow.com/users/14268186/hupo)
4933 bronze badges
## Comments
Add a comment
This answer is useful
\-1
Save this answer.
Show activity on this post.
In Python or in any other language we have a type for every variable or object we declare. For getting type of anything(variable,object,etc.) in Python we can use type() function.
Bypassing the metaclass keyword in the class definition we can customize the class creation process.
```
Copy
```
When defining a new class if no metaclass is defined the default type metaclass is used. If a given metaclass is not the object(instance) of type(), in that situation it is used directly as a metaclass.
[Share](https://stackoverflow.com/a/75343419 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/75343419/edit)
Follow
Follow this answer to receive notifications
answered Feb 4, 2023 at 6:35
[](https://stackoverflow.com/users/20979763/neha-sharma)
[Neha Sharma](https://stackoverflow.com/users/20979763/neha-sharma)
3644 bronze badges
## Comments
Add a comment
**[Protected question](https://stackoverflow.com/help/privileges/protect-questions)**. To answer this question, you need to have at least 10 reputation on this site (not counting the [association bonus](https://meta.stackexchange.com/questions/141648/what-is-the-association-bonus-and-how-does-it-work)). The reputation requirement helps protect this question from spam and non-answer activity.
Start asking to get answers
Find the answer to your question by asking.
[Ask question](https://stackoverflow.com/questions/ask)
Explore related questions
- [python](https://stackoverflow.com/questions/tagged/python "show questions tagged 'python'")
- [oop](https://stackoverflow.com/questions/tagged/oop "show questions tagged 'oop'")
- [metaclass](https://stackoverflow.com/questions/tagged/metaclass "show questions tagged 'metaclass'")
- [python-class](https://stackoverflow.com/questions/tagged/python-class "show questions tagged 'python-class'")
- [python-datamodel](https://stackoverflow.com/questions/tagged/python-datamodel "show questions tagged 'python-datamodel'")
See similar questions with these tags.
- The Overflow Blog
- [At AWS re:Invent, the news was agents, but the focus was developers](https://stackoverflow.blog/2025/12/15/at-aws-re-invent-the-news-was-agents-but-the-focus-was-developers/?cb=1)
- [Live from re:Invent…it’s Stack Overflow\!](https://stackoverflow.blog/2025/12/16/live-from-re-invent-it-s-stack-overflow/?cb=1)
- Featured on Meta
- [AI Assist is now available on Stack Overflow](https://meta.stackexchange.com/questions/415115/ai-assist-is-now-available-on-stack-overflow?cb=1)
- [Native Ads coming soon to Stack Overflow and Stack Exchange](https://meta.stackexchange.com/questions/415259/native-ads-coming-soon-to-stack-overflow-and-stack-exchange?cb=1)
- [Policy: Generative AI (e.g., ChatGPT) is banned](https://meta.stackoverflow.com/questions/421831/policy-generative-ai-e-g-chatgpt-is-banned?cb=1)
Community activity
Last 1 hr
- Users online activity
18163 users online
- 27 questions
- 20 answers
- 52 comments
- 316 upvotes
Popular tags
[c](https://stackoverflow.com/questions/tagged/c)[c\#](https://stackoverflow.com/questions/tagged/c)[android](https://stackoverflow.com/questions/tagged/android)[c++](https://stackoverflow.com/questions/tagged/c++)[java](https://stackoverflow.com/questions/tagged/java)[python](https://stackoverflow.com/questions/tagged/python)
Popular unanswered question
[Building Restful Web Service using Spark Java for Library Management System](https://stackoverflow.com/questions/34461253)
[java](https://stackoverflow.com/questions/tagged/java)[jquery](https://stackoverflow.com/questions/tagged/jquery)[html](https://stackoverflow.com/questions/tagged/html)[ajax](https://stackoverflow.com/questions/tagged/ajax)
[](https://stackoverflow.com/users/5716187)
[B Chauhan](https://stackoverflow.com/users/5716187)
- 21
3,644 days ago
#### Linked
[161](https://stackoverflow.com/questions/18126552/how-to-run-code-when-a-class-is-subclassed?lq=1 "Question score (upvotes - downvotes)")
[How to run code when a class is subclassed?](https://stackoverflow.com/questions/18126552/how-to-run-code-when-a-class-is-subclassed?noredirect=1&lq=1)
[96](https://stackoverflow.com/questions/17801344/understanding-metaclass-and-inheritance-in-python?lq=1 "Question score (upvotes - downvotes)")
[Understanding metaclass and inheritance in Python](https://stackoverflow.com/questions/17801344/understanding-metaclass-and-inheritance-in-python?noredirect=1&lq=1)
[40](https://stackoverflow.com/questions/19463598/how-are-python-metaclasses-different-from-regular-class-inheritance?lq=1 "Question score (upvotes - downvotes)")
[How are Python metaclasses different from regular class inheritance?](https://stackoverflow.com/questions/19463598/how-are-python-metaclasses-different-from-regular-class-inheritance?noredirect=1&lq=1)
[29](https://stackoverflow.com/questions/15715612/what-is-the-difference-between-a-type-and-an-object-in-python?lq=1 "Question score (upvotes - downvotes)")
[What is the difference between a 'Type' and an 'Object' in Python](https://stackoverflow.com/questions/15715612/what-is-the-difference-between-a-type-and-an-object-in-python?noredirect=1&lq=1)
[37](https://stackoverflow.com/questions/34961221/can-we-overload-behavior-of-class-object?lq=1 "Question score (upvotes - downvotes)")
[Can we overload behavior of class object](https://stackoverflow.com/questions/34961221/can-we-overload-behavior-of-class-object?noredirect=1&lq=1)
[15](https://stackoverflow.com/questions/35723207/how-does-one-create-a-metaclass?lq=1 "Question score (upvotes - downvotes)")
[How does one create a metaclass?](https://stackoverflow.com/questions/35723207/how-does-one-create-a-metaclass?noredirect=1&lq=1)
[10](https://stackoverflow.com/questions/16377453/why-are-django-model-classes-not-of-type-type?lq=1 "Question score (upvotes - downvotes)")
[Why are django model classes not of type "type"?](https://stackoverflow.com/questions/16377453/why-are-django-model-classes-not-of-type-type?noredirect=1&lq=1)
[12](https://stackoverflow.com/questions/24615611/what-is-the-difference-between-abstract-classes-and-metaclasses-in-python?lq=1 "Question score (upvotes - downvotes)")
[What is the difference between Abstract Classes and Metaclasses in python?](https://stackoverflow.com/questions/24615611/what-is-the-difference-between-abstract-classes-and-metaclasses-in-python?noredirect=1&lq=1)
[4](https://stackoverflow.com/questions/44080357/use-of-isinstance-can-overwrite-type?lq=1 "Question score (upvotes - downvotes)")
[Use of isinstance() can overwrite type](https://stackoverflow.com/questions/44080357/use-of-isinstance-can-overwrite-type?noredirect=1&lq=1)
[8](https://stackoverflow.com/questions/47984772/python-metaclass-new-method-not-getting-called?lq=1 "Question score (upvotes - downvotes)")
[Python Metaclass \_\_new\_\_ method not getting called](https://stackoverflow.com/questions/47984772/python-metaclass-new-method-not-getting-called?noredirect=1&lq=1)
[See more linked questions](https://stackoverflow.com/questions/linked/100003?lq=1)
#### Related
[6](https://stackoverflow.com/questions/618960/python-metaclasses?rq=3 "Question score (upvotes - downvotes)")
[Python metaclasses](https://stackoverflow.com/questions/618960/python-metaclasses?rq=3)
[3](https://stackoverflow.com/questions/11385521/metaclass-and-syntax-in-python?rq=3 "Question score (upvotes - downvotes)")
[Metaclass and syntax in Python](https://stackoverflow.com/questions/11385521/metaclass-and-syntax-in-python?rq=3)
[2](https://stackoverflow.com/questions/14765780/is-a-class-or-instance-in-the-meta-class?rq=3 "Question score (upvotes - downvotes)")
[Is a class or instance in the meta class?](https://stackoverflow.com/questions/14765780/is-a-class-or-instance-in-the-meta-class?rq=3)
[2](https://stackoverflow.com/questions/21659360/python-metaclasses-confusion?rq=3 "Question score (upvotes - downvotes)")
[Python metaclasses confusion](https://stackoverflow.com/questions/21659360/python-metaclasses-confusion?rq=3)
[3](https://stackoverflow.com/questions/23879910/special-usage-of-metaclasses-in-python?rq=3 "Question score (upvotes - downvotes)")
[Special usage of metaclasses in python](https://stackoverflow.com/questions/23879910/special-usage-of-metaclasses-in-python?rq=3)
[1](https://stackoverflow.com/questions/39879345/what-are-metaclass-bases-in-python?rq=3 "Question score (upvotes - downvotes)")
[What are metaclass bases in Python?](https://stackoverflow.com/questions/39879345/what-are-metaclass-bases-in-python?rq=3)
[2](https://stackoverflow.com/questions/49248732/built-in-classes-metaclass-in-python?rq=3 "Question score (upvotes - downvotes)")
[Built-in classes metaclass in Python](https://stackoverflow.com/questions/49248732/built-in-classes-metaclass-in-python?rq=3)
[0](https://stackoverflow.com/questions/51395847/understanding-meta-classes-in-python?rq=3 "Question score (upvotes - downvotes)")
[Understanding Meta classes in python](https://stackoverflow.com/questions/51395847/understanding-meta-classes-in-python?rq=3)
[4](https://stackoverflow.com/questions/66499554/what-is-the-difference-between-type-class-and-object-class-in-python?rq=3 "Question score (upvotes - downvotes)")
[what is the difference between type class and object class in python](https://stackoverflow.com/questions/66499554/what-is-the-difference-between-type-class-and-object-class-in-python?rq=3)
[0](https://stackoverflow.com/questions/73249141/are-there-any-unique-features-provided-only-by-metaclasses-in-python?rq=3 "Question score (upvotes - downvotes)")
[Are there any unique features provided only by metaclasses in Python?](https://stackoverflow.com/questions/73249141/are-there-any-unique-features-provided-only-by-metaclasses-in-python?rq=3)
#### [Hot Network Questions](https://stackexchange.com/questions?tab=hot)
- [2016 Honda CR-V AWD windshield washer](https://mechanics.stackexchange.com/questions/101779/2016-honda-cr-v-awd-windshield-washer)
- [why don't blended wing body aircraft use columns inside the pressurized compartment to improve strength against compression forces?](https://aviation.stackexchange.com/questions/114745/why-dont-blended-wing-body-aircraft-use-columns-inside-the-pressurized-compartm)
- [What is the closest type (in information theoretic sense) that type I and type II errors depend on?](https://stats.stackexchange.com/questions/673913/what-is-the-closest-type-in-information-theoretic-sense-that-type-i-and-type-i)
- [Custom shaped torus spiral](https://blender.stackexchange.com/questions/343982/custom-shaped-torus-spiral)
- [Why can't angular velocity be a scalar quantity in 3D?](https://physics.stackexchange.com/questions/866679/why-cant-angular-velocity-be-a-scalar-quantity-in-3d)
- [I'm facing an issue where Google shows the wrong site logo in search results](https://webmasters.stackexchange.com/questions/148360/im-facing-an-issue-where-google-shows-the-wrong-site-logo-in-search-results)
- [Why is a free verse poem not prose?](https://literature.stackexchange.com/questions/31186/why-is-a-free-verse-poem-not-prose)
- [What might cause CAN bus low voltage?](https://electronics.stackexchange.com/questions/763172/what-might-cause-can-bus-low-voltage)
- [PSE Advent Calendar 2025 (Day 14): The Great Paper Caper](https://puzzling.stackexchange.com/questions/136300/pse-advent-calendar-2025-day-14-the-great-paper-caper)
- [What does it mean when physicists say: "an object rotate around any point you choose "?](https://physics.stackexchange.com/questions/866729/what-does-it-mean-when-physicists-say-an-object-rotate-around-any-point-you-ch)
- [Fillet Curve with Per-Corner Radii for selected index](https://blender.stackexchange.com/questions/343953/fillet-curve-with-per-corner-radii-for-selected-index)
- [Managing a paralyzing backlog of "potentially useful" math papers to read](https://academia.stackexchange.com/questions/225345/managing-a-paralyzing-backlog-of-potentially-useful-math-papers-to-read)
- [How to iterate flat\_map in range-based for loop updating values?](https://stackoverflow.com/questions/79847808/how-to-iterate-flat-map-in-range-based-for-loop-updating-values)
- [Can shields block AOE attacks?](https://gaming.stackexchange.com/questions/417368/can-shields-block-aoe-attacks)
- [Sequences of irreducible polynomials](https://mathoverflow.net/questions/505962/sequences-of-irreducible-polynomials)
- [Including graphics in a Latex document](https://tex.stackexchange.com/questions/757173/including-graphics-in-a-latex-document)
- [Is it correct English to say "go straight at \[a place\]"?](https://ell.stackexchange.com/questions/373454/is-it-correct-english-to-say-go-straight-at-a-place)
- [Bash Backup script for password DB - Improved](https://codereview.stackexchange.com/questions/300756/bash-backup-script-for-password-db-improved)
- [Function with asymmetric CPU usage](https://crypto.stackexchange.com/questions/119179/function-with-asymmetric-cpu-usage)
- [Why does \\changefontsize from the fontsize package mess with \\centering?](https://tex.stackexchange.com/questions/757122/why-does-changefontsize-from-the-fontsize-package-mess-with-centering)
- [Why would one reset local variables at the end of a C function?](https://stackoverflow.com/questions/79846996/why-would-one-reset-local-variables-at-the-end-of-a-c-function)
- [How to deal with uncertainty and speak in uncertain terms?](https://philosophy.stackexchange.com/questions/134473/how-to-deal-with-uncertainty-and-speak-in-uncertain-terms)
- [What character is this?](https://chinese.stackexchange.com/questions/63815/what-character-is-this)
- [Does the order of passengers in a flight booking matter?](https://travel.stackexchange.com/questions/202831/does-the-order-of-passengers-in-a-flight-booking-matter)
[Question feed](https://stackoverflow.com/feeds/question/100003 "Feed of this question and its answers")
# Subscribe to RSS
Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-py
# Why are you flagging this comment?
Probable spam.
This comment promotes a product, service or website while [failing to disclose the author's affiliation](https://stackoverflow.com/help/promotion).
Unfriendly or contains harassment/bigotry/abuse.
This comment is unkind, insulting or attacks another person or group. Learn more in our [Abusive behavior policy](https://stackoverflow.com/conduct/abusive-behavior).
Not needed.
This comment is not relevant to the post.
```
```
Enter at least 6 characters
Something else.
A problem not listed above. Try to be as specific as possible.
```
```
Enter at least 6 characters
Flag comment
Cancel
You have 0 flags left today
# 
# Hang on, you can't upvote just yet.
You'll need to complete a few actions and gain 15 reputation points before being able to upvote. **Upvoting** indicates when questions and answers are useful. [What's reputation and how do I get it?](https://stackoverflow.com/help/whats-reputation)
Instead, you can save this post to reference later.
Save this post for later
Not now
##### [Stack Overflow](https://stackoverflow.com/)
- [Questions](https://stackoverflow.com/questions)
- [Help](https://stackoverflow.com/help)
- [Chat](https://chat.stackoverflow.com/?tab=explore)
##### [Business](https://stackoverflow.co/)
- [Stack Internal](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=teams)
- [Stack Data Licensing](https://stackoverflow.co/data-licensing/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=data-licensing)
- [Stack Ads](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=advertising)
##### [Company](https://stackoverflow.co/)
- [About](https://stackoverflow.co/)
- [Press](https://stackoverflow.co/company/press/)
- [Work Here](https://stackoverflow.co/company/work-here/)
- [Legal](https://stackoverflow.com/legal)
- [Privacy Policy](https://stackoverflow.com/legal/privacy-policy)
- [Terms of Service](https://stackoverflow.com/legal/terms-of-service/public)
- [Contact Us](https://stackoverflow.com/contact)
- Cookie Settings
- [Cookie Policy](https://policies.stackoverflow.co/stack-overflow/cookie-policy)
##### [Stack Exchange Network](https://stackexchange.com/)
- [Technology](https://stackexchange.com/sites#technology)
- [Culture & recreation](https://stackexchange.com/sites#culturerecreation)
- [Life & arts](https://stackexchange.com/sites#lifearts)
- [Science](https://stackexchange.com/sites#science)
- [Professional](https://stackexchange.com/sites#professional)
- [Business](https://stackexchange.com/sites#business)
- [API](https://api.stackexchange.com/)
- [Data](https://data.stackexchange.com/)
- [Blog](https://stackoverflow.blog/?blb=1)
- [Facebook](https://www.facebook.com/officialstackoverflow/)
- [Twitter](https://twitter.com/stackoverflow)
- [LinkedIn](https://linkedin.com/company/stack-overflow)
- [Instagram](https://www.instagram.com/thestackoverflow)
Site design / logo © 2025 Stack Exchange Inc; user contributions licensed under [CC BY-SA](https://stackoverflow.com/help/licensing) . rev 2025.12.15.38091 |
| Readable Markdown | null |
| Shard | 169 (laksa) |
| Root Hash | 714406497480128969 |
| Unparsed URL | com,stackoverflow!/questions/100003/what-are-metaclasses-in-python s443 |