ℹ️ 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 | 5.4 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/392160/what-are-some-concrete-use-cases-for-metaclasses |
| Last Crawled | 2025-11-01 07:50:48 (5 months ago) |
| First Indexed | 2018-07-31 12:03:49 (7 years ago) |
| HTTP Status Code | 200 |
| Meta Title | python - What are some (concrete) use-cases for metaclasses? - Stack Overflow |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | I was asked the same question recently, and came up with several answers. I hope it's OK to revive this thread, as I wanted to elaborate on a few of the use cases mentioned, and add a few new ones. Most metaclasses I've seen do one of two things: Registration (adding a class to a data structure): models = {}
class ModelMetaclass ( type ):
def __new__ ( meta, name, bases, attrs ):
models[name] = cls = type .__new__(meta, name, bases, attrs)
return cls
class Model ( object ):
__metaclass__ = ModelMetaclass
Whenever you subclass Model , your class is registered in the models dictionary: >>> class A ( Model ):
... pass
...
>>> class B ( A ):
... pass
...
>>> models
{ 'A' : <__main__.A class at 0x...>,
'B' : <__main__.B class at 0x...>}
This can also be done with class decorators: models = {}
def model ( cls ):
models[cls.__name__] = cls
return cls
@model class A ( object ):
pass Or with an explicit registration function: models = {}
def register_model ( cls ):
models[cls.__name__] = cls
class A ( object ):
pass
register_model(A)
Actually, this is pretty much the same: you mention class decorators unfavorably, but it's really nothing more than syntactic sugar for a function invocation on a class, so there's no magic about it. Anyway, the advantage of metaclasses in this case is inheritance, as they work for any subclasses, whereas the other solutions only work for subclasses explicitly decorated or registered. >>> class B ( A ):
... pass
...
>>> models
{ 'A' : <__main__.A class at 0x...> Refactoring (modifying class attributes or adding new ones): class ModelMetaclass ( type ):
def __new__ ( meta, name, bases, attrs ):
fields = {}
for key, value in attrs.items():
if isinstance (value, Field):
value.name = '%s.%s' % (name, key)
fields[key] = value
for base in bases:
if hasattr (base, '_fields' ):
fields.update(base._fields)
attrs[ '_fields' ] = fields
return type .__new__(meta, name, bases, attrs)
class Model ( object ):
__metaclass__ = ModelMetaclass
Whenever you subclass Model and define some Field attributes, they are injected with their names (for more informative error messages, for example), and grouped into a _fields dictionary (for easy iteration, without having to look through all the class attributes and all its base classes' attributes every time): >>> class A ( Model ):
... foo = Integer()
...
>>> class B ( A ):
... bar = String()
...
>>> B._fields
{ 'foo' : Integer( 'A.foo' ), 'bar' : String( 'B.bar' )}
Again, this can be done (without inheritance) with a class decorator: def model ( cls ):
fields = {}
for key, value in vars (cls).items():
if isinstance (value, Field):
value.name = '%s.%s' % (cls.__name__, key)
fields[key] = value
for base in cls.__bases__:
if hasattr (base, '_fields' ):
fields.update(base._fields)
cls._fields = fields
return cls
@model class A ( object ):
foo = Integer()
class B ( A ):
bar = String()
Or explicitly: class A ( object ):
foo = Integer( 'A.foo' )
_fields = { 'foo' : foo} Although, on the contrary to your advocacy for readable and maintainable non-meta programming, this is much more cumbersome, redundant and error prone: class B ( A ):
bar = String()
class B ( A ):
bar = String( 'bar' )
_fields = { 'B.bar' : bar, 'A.foo' : A.foo}
Having considered the most common and concrete use cases, the only cases where you absolutely HAVE to use metaclasses are when you want to modify the class name or list of base classes, because once defined, these parameters are baked into the class, and no decorator or function can unbake them. class Metaclass ( type ):
def __new__ ( meta, name, bases, attrs ):
return type .__new__(meta, 'foo' , ( int ,), attrs)
class Baseclass ( object ):
__metaclass__ = Metaclass
class A ( Baseclass ):
pass class B ( A ):
pass print A.__name__ print B.__name__ print issubclass (B, A) print issubclass (B, int ) This may be useful in frameworks for issuing warnings whenever classes with similar names or incomplete inheritance trees are defined, but I can't think of a reason beside trolling to actually change these values. Maybe David Beazley can. Anyway, in Python 3, metaclasses also have the __prepare__ method, which lets you evaluate the class body into a mapping other than a dict , thus supporting ordered attributes, overloaded attributes, and other wicked cool stuff: import collections
class Metaclass ( type ):
@classmethod def __prepare__ ( meta, name, bases, **kwds ):
return collections.OrderedDict()
def __new__ ( meta, name, bases, attrs, **kwds ):
print ( list (attrs))
class A (metaclass=Metaclass):
x = 1
y = 2 class ListDict ( dict ):
def __setitem__ ( self, key, value ):
self.setdefault(key, []).append(value)
class Metaclass ( type ):
@classmethod def __prepare__ ( meta, name, bases, **kwds ):
return ListDict()
def __new__ ( meta, name, bases, attrs, **kwds ):
print (attrs[ 'foo' ])
class A (metaclass=Metaclass):
def foo ( self ):
pass def foo ( self, x ):
pass You might argue ordered attributes can be achieved with creation counters, and overloading can be simulated with default arguments: import itertools
class Attribute ( object ):
_counter = itertools.count()
def __init__ ( self ):
self._count = Attribute._counter. next ()
class A ( object ):
x = Attribute()
y = Attribute()
A._order = sorted ([(k, v) for k, v in vars (A).items() if isinstance (v, Attribute)],
key = lambda (k, v): v._count)
class A ( object ):
def _foo0 ( self ):
pass def _foo1 ( self, x ):
pass def foo ( self, x= None ):
if x is None :
return self._foo0()
else :
return self._foo1(x)
Besides being much more ugly, it's also less flexible: what if you want ordered literal attributes, like integers and strings? What if None is a valid value for x ? Here's a creative way to solve the first problem: import sys
class Builder ( object ):
def __call__ ( self, cls ):
cls._order = self.frame.f_code.co_names
return cls
def ordered ():
builder = Builder()
def trace ( frame, event, arg ):
builder.frame = frame
sys.settrace( None )
sys.settrace(trace)
return builder
@ordered() class A ( object ):
x = 1
y = 'foo' print A._order And here's a creative way to solve the second one: _undefined = object ()
class A ( object ):
def _foo0 ( self ):
pass def _foo1 ( self, x ):
pass def foo ( self, x=_undefined ):
if x is _undefined:
return self._foo0()
else :
return self._foo1(x)
But this is much, MUCH voodoo-er than a simple metaclass (especially the first one, which really melts your brain). My point is, you look at metaclasses as unfamiliar and counter-intuitive, but you can also look at them as the next step of evolution in programming languages: you just have to adjust your mindset. After all, you could probably do everything in C, including defining a struct with function pointers and passing it as the first argument to its functions. A person seeing C++ for the first time might say, "what is this magic? Why is the compiler implicitly passing this to methods, but not to regular and static functions? It's better to be explicit and verbose about your arguments". But then, object-oriented programming is much more powerful once you get it; and so is this, uh... quasi-aspect-oriented programming, I guess. And once you understand metaclasses, they're actually very simple, so why not use them when convenient? And finally, metaclasses are rad, and programming should be fun. Using standard programming constructs and design patterns all the time is boring and uninspiring, and hinders your imagination. Live a little! Here's a metametaclass, just for you. class MetaMetaclass ( type ):
def __new__ ( meta, name, bases, attrs ):
def __new__ ( meta, name, bases, attrs ):
cls = type .__new__(meta, name, bases, attrs)
cls._label = 'Made in %s' % meta.__name__
return cls
attrs[ '__new__' ] = __new__
return type .__new__(meta, name, bases, attrs)
class China ( type ):
__metaclass__ = MetaMetaclass
class Taiwan ( type ):
__metaclass__ = MetaMetaclass
class A ( object ):
__metaclass__ = China
class B ( object ):
__metaclass__ = Taiwan
print A._label print B._label This is a pretty old question, but it's still getting upvotes, so I thought I'd add a link to a more comprehensive answer. If you'd like to read more about metaclasses and their uses, I've just published an article about it here . |
| 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/392160/what-are-some-concrete-use-cases-for-metaclasses#content)
[Stack Overflow](https://stackoverflow.com/)
1. [About](https://stackoverflow.co/)
2. Products
3. [For Teams](https://stackoverflow.co/teams/)
1. [Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-for-teams)
2. [Advertising Reach devs & technologists worldwide about your product, service or employer brand](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-advertising)
3. [Knowledge Solutions Data licensing offering for businesses to build and improve AI tools and models](https://stackoverflow.co/api-solutions/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=overflow-api)
4. [Labs The future of collective knowledge sharing](https://stackoverflow.co/labs/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=labs)
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%2F392160%2Fwhat-are-some-concrete-use-cases-for-metaclasses) or [log in](https://stackoverflow.com/users/login?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F392160%2Fwhat-are-some-concrete-use-cases-for-metaclasses) 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%2F392160%2Fwhat-are-some-concrete-use-cases-for-metaclasses)
3. [Sign up](https://stackoverflow.com/users/signup?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F392160%2Fwhat-are-some-concrete-use-cases-for-metaclasses)
# 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
- jenkins
- testing
- 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
- session
- rust
- intellij-idea
- hadoop
- curl
- next.js
- join
- winapi
- django-models
- laravel-5
- url
- heroku
- http-redirect
- tomcat
- google-cloud-firestore
- inheritance
- webpack
- image-processing
- gcc
- keras
- swiftui
- 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
- audio
- multidimensional-array
- random
- jsf
- vector
- redux
- cookies
- input
- facebook-graph-api
- flash
- indexing
- xamarin.forms
- arraylist
- ipad
- cocoa-touch
- data-structures
- video
- azure-devops
- model-view-controller
- apache-kafka
- serialization
- jdbc
- woocommerce
- razor
- routes
- awk
- servlets
- mod-rewrite
- excel-formula
- beautifulsoup
- filter
- docker-compose
- iframe
- aws-lambda
- design-patterns
- text
- visual-c++
- django-rest-framework
- cakephp
- mobile
- android-intent
- struct
- react-hooks
- methods
- groovy
- mvvm
- ssh
- lambda
- 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
- activerecord
- bootstrap-4
- websocket
- graph
- replace
- group-by
- scikit-learn
- vim
- file-upload
- junit
- boost
- memory-management
- sass
- import
- async-await
- 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
- mysqli
- entity-framework-core
- concurrency
- command-line
- spring-data-jpa
- printing
- react-redux
- java-8
- lua
- html-table
- ansible
- neo4j
- jestjs
- service
- parameters
- enums
- material-ui
- flexbox
- module
- promise
- visual-studio-2012
- outlook
- firebase-authentication
- web-applications
- 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
- three.js
- paypal
- powerbi
- graphql
- cassandra
- discord
- graphics
- compiler-errors
- gwt
- socket.io
- react-router
- solr
- backbone.js
- url-rewriting
- memory-leaks
- datatables
- nlp
- terraform
- oauth
- datagridview
- drupal
- zend-framework
- oracle11g
- knockout.js
- triggers
- neural-network
- interface
- django-forms
- angular-material
- casting
- jmeter
- google-api
- linked-list
- path
- timer
- arduino
- django-templates
- proxy
- orm
- directory
- windows-phone-7
- parse-platform
- visual-studio-2015
- cron
- conditional-statements
- push-notification
- functional-programming
- primefaces
- pagination
- model
- jar
- xamarin.android
- hyperlink
- uiview
- visual-studio-2013
- vbscript
- google-cloud-functions
- gitlab
- azure-active-directory
- jwt
- download
- swift3
- sql-server-2005
- process
- configuration
- rspec
- pygame
- properties
- combobox
- callback
- windows-phone-8
- linux-kernel
- safari
- scrapy
- permissions
- emacs
- clojure
- raspberry-pi
- scripting
- x86
- scope
- io
- expo
- azure-functions
- compilation
- responsive-design
- mongodb-query
- nhibernate
- angularjs-directive
- request
- bluetooth
- reference
- binding
- dns
- architecture
- 3d
- playframework
- pyqt
- 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
- statistics
- transactions
- active-directory
- datagrid
- dockerfile
- uiviewcontroller
- webforms
- discord.py
- phpmyadmin
- sas
- computer-vision
- notifications
- duplicates
- mocking
- youtube
- pycharm
- yaml
- nullpointerexception
- menu
- blazor
- sum
- plotly
- bitmap
- asp.net-mvc-5
- visual-studio-2008
- yii2
- floating-point
- electron
- css-selectors
- stl
- jsf-2
- android-listview
- time-series
- cryptography
- ant
- hashmap
- character-encoding
- stream
- msbuild
- asp.net-core-mvc
- sdk
- google-drive-api
- jboss
- selenium-chromedriver
- joomla
- devise
- cors
- navigation
- anaconda
- cuda
- background
- frontend
- multiprocessing
- binary
- pyqt5
- camera
- iterator
- linq-to-sql
- mariadb
- onclick
- android-jetpack-compose
- ios7
- microsoft-graph-api
- rabbitmq
- android-asynctask
- tabs
- laravel-4
- environment-variables
- amazon-dynamodb
- insert
- uicollectionview
- linker
- xsd
- coldfusion
- console
- continuous-integration
- upload
- textview
- ftp
- opengl-es
- macros
- operating-system
- mockito
- localization
- formatting
- xml-parsing
- vuejs3
- json.net
- type-conversion
- data.table
- kivy
- timestamp
- integer
- calendar
- segmentation-fault
- android-ndk
- prolog
- drag-and-drop
- char
- crash
- jasmine
- dependencies
- automated-tests
- geometry
- azure-pipelines
- android-gradle-plugin
- fortran
- itext
- sprite-kit
- header
- mfc
- firebase-cloud-messaging
- attributes
- format
- nosql
- nuxt.js
- odoo
- db2
- jquery-plugins
- event-handling
- jenkins-pipeline
- julia
- nestjs
- leaflet
- annotations
- flutter-layout
- keyboard
- postman
- textbox
- arm
- visual-studio-2017
- gulp
- stripe-payments
- libgdx
- synchronization
- timezone
- uikit
- azure-web-app-service
- dom-events
- xampp
- wso2
- crystal-reports
- swagger
- namespaces
- android-emulator
- aggregation-framework
- uiscrollview
- jvm
- google-sheets-formula
- sequelize.js
- chart.js
- com
- snowflake-cloud-data-platform
- subprocess
- geolocation
- webdriver
- html5-canvas
- garbage-collection
- centos
- dialog
- sql-update
- widget
- numbers
- concatenation
- qml
- set
- tuples
- java-stream
- smtp
- mapreduce
- ionic2
- windows-10
- rotation
- android-edittext
- modal-dialog
- spring-data
- nuget
- doctrine
- radio-button
- http-headers
- grid
- sonarqube
- lucene
- xmlhttprequest
- listbox
- switch-statement
- initialization
- internationalization
- components
- apache-camel
- boolean
- google-play
- serial-port
- gdb
- ios5
- ldap
- return
- youtube-api
- pivot
- eclipse-plugin
- latex
- frameworks
- tags
- containers
- github-actions
- c++17
- subquery
- dataset
- asp-classic
- foreign-keys
- label
- embedded
- uinavigationcontroller
- copy
- delegates
- struts2
- google-cloud-storage
- migration
- protractor
- base64
- queue
- find
- uibutton
- sql-server-2008-r2
- arguments
- composer-php
- append
- jaxb
- stack
- zip
- tailwind-css
- cucumber
- autolayout
- ide
- entity-framework-6
- iteration
- popup
- r-markdown
- windows-7
- airflow
- vb6
- g++
- ssl-certificate
- hover
- clang
- 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 Labs](https://stackoverflow.ai/)
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. Teams

Ask questions, find answers and collaborate at work with Stack Overflow for Teams.
[Try Teams for free](https://stackoverflowteams.com/teams/create/free/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams) [Explore Teams](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams)
3. [Teams]()
4. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. [Explore Teams](https://stackoverflow.co/teams/?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)
**Teams**
Q\&A for work
Connect and share knowledge within a single location that is structured and easy to search.
[Learn more about Teams](https://stackoverflow.co/teams/)
# 
# 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
# 
# Thanks for your vote! You now have 5 free votes weekly.
Free votes
- count toward the total vote score
- does not give reputation to the author
Continue to help good content that is interesting, well-researched, and useful, rise to the top! To gain full voting privileges, [earn reputation](https://stackoverflow.com/help/whats-reputation).
Got it\!
Go to help center to learn more
# [What are some (concrete) use-cases for metaclasses?](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses)
[Ask Question](https://stackoverflow.com/questions/ask)
Asked
16 years, 9 months ago
Modified [3 years, 10 months ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses?lastactivity "2021-11-20 14:42:36Z")
Viewed 45k times
This question shows research effort; it is useful and clear
185
Save this question.
Show activity on this post.
I have a friend who likes to use metaclasses, and regularly offers them as a solution.
I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.
Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.
So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.
I will start:
> Sometimes when using a third-party library it is useful to be able to mutate the class in a certain way.
(This is the only case I can think of, and it's not concrete)
- [python](https://stackoverflow.com/questions/tagged/python "show questions tagged 'python'")
- [metaclass](https://stackoverflow.com/questions/tagged/metaclass "show questions tagged 'metaclass'")
[Share](https://stackoverflow.com/q/392160 "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/392160/edit)
Follow
Follow this question to receive notifications
[edited Jun 29, 2018 at 21:18](https://stackoverflow.com/posts/392160/revisions "show all edits to this post")
[](https://stackoverflow.com/users/355230/martineau)
[martineau](https://stackoverflow.com/users/355230/martineau)
124k2929 gold badges180180 silver badges318318 bronze badges
asked Dec 24, 2008 at 20:13
[](https://stackoverflow.com/users/28380/ali-afshar)
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)Ali Afshar
41\.8k1212 gold badges9797 silver badges111111 bronze badges
2
- 7
This is a great question. Judging from the answers below, its quite clear that there are no such thing as a concrete use for metaclasses.
Marcus Ottosson
– [Marcus Ottosson](https://stackoverflow.com/users/478949/marcus-ottosson "3,321 reputation")
2014-02-14 17:49:30 +00:00
[Commented Feb 14, 2014 at 17:49](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment32961859_392160)
- @MarcusOttosson no, obfuscating your code is a pretty good use for them.
Nathan Chappell
– [Nathan Chappell](https://stackoverflow.com/users/6084517/nathan-chappell "2,532 reputation")
2023-02-22 14:50:21 +00:00
[Commented Feb 22, 2023 at 14:50](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment133266468_392160)
[Add a comment](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses "Use comments to ask for more information or suggest improvements. Avoid answering questions in comments.") \|
## 21 Answers 21
Sorted by:
[Reset to default](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses?answertab=scoredesc#tab-top)
This answer is useful
175
Save this answer.
Show activity on this post.
I was asked the same question recently, and came up with several answers. I hope it's OK to revive this thread, as I wanted to elaborate on a few of the use cases mentioned, and add a few new ones.
Most metaclasses I've seen do one of two things:
1. Registration (adding a class to a data structure):
```
models = {}
class ModelMetaclass(type):
def __new__(meta, name, bases, attrs):
models[name] = cls = type.__new__(meta, name, bases, attrs)
return cls
class Model(object):
__metaclass__ = ModelMetaclass
```
Whenever you subclass `Model`, your class is registered in the `models` dictionary:
```
>>> class A(Model):
... pass
...
>>> class B(A):
... pass
...
>>> models
{'A': <__main__.A class at 0x...>,
'B': <__main__.B class at 0x...>}
```
This can also be done with class decorators:
```
models = {}
def model(cls):
models[cls.__name__] = cls
return cls
@model
class A(object):
pass
```
Or with an explicit registration function:
```
models = {}
def register_model(cls):
models[cls.__name__] = cls
class A(object):
pass
register_model(A)
```
Actually, this is pretty much the same: you mention class decorators unfavorably, but it's really nothing more than syntactic sugar for a function invocation on a class, so there's no magic about it.
Anyway, the advantage of metaclasses in this case is inheritance, as they work for any subclasses, whereas the other solutions only work for subclasses explicitly decorated or registered.
```
>>> class B(A):
... pass
...
>>> models
{'A': <__main__.A class at 0x...> # No B :(
```
2. Refactoring (modifying class attributes or adding new ones):
```
class ModelMetaclass(type):
def __new__(meta, name, bases, attrs):
fields = {}
for key, value in attrs.items():
if isinstance(value, Field):
value.name = '%s.%s' % (name, key)
fields[key] = value
for base in bases:
if hasattr(base, '_fields'):
fields.update(base._fields)
attrs['_fields'] = fields
return type.__new__(meta, name, bases, attrs)
class Model(object):
__metaclass__ = ModelMetaclass
```
Whenever you subclass `Model` and define some `Field` attributes, they are injected with their names (for more informative error messages, for example), and grouped into a `_fields` dictionary (for easy iteration, without having to look through all the class attributes and all its base classes' attributes every time):
```
>>> class A(Model):
... foo = Integer()
...
>>> class B(A):
... bar = String()
...
>>> B._fields
{'foo': Integer('A.foo'), 'bar': String('B.bar')}
```
Again, this can be done (without inheritance) with a class decorator:
```
def model(cls):
fields = {}
for key, value in vars(cls).items():
if isinstance(value, Field):
value.name = '%s.%s' % (cls.__name__, key)
fields[key] = value
for base in cls.__bases__:
if hasattr(base, '_fields'):
fields.update(base._fields)
cls._fields = fields
return cls
@model
class A(object):
foo = Integer()
class B(A):
bar = String()
# B.bar has no name :(
# B._fields is {'foo': Integer('A.foo')} :(
```
Or explicitly:
```
class A(object):
foo = Integer('A.foo')
_fields = {'foo': foo} # Don't forget all the base classes' fields, too!
```
Although, on the contrary to your advocacy for readable and maintainable non-meta programming, this is much more cumbersome, redundant and error prone:
```
class B(A):
bar = String()
# vs.
class B(A):
bar = String('bar')
_fields = {'B.bar': bar, 'A.foo': A.foo}
```
Having considered the most common and concrete use cases, the only cases where you absolutely HAVE to use metaclasses are when you want to modify the class name or list of base classes, because once defined, these parameters are baked into the class, and no decorator or function can unbake them.
```
class Metaclass(type):
def __new__(meta, name, bases, attrs):
return type.__new__(meta, 'foo', (int,), attrs)
class Baseclass(object):
__metaclass__ = Metaclass
class A(Baseclass):
pass
class B(A):
pass
print A.__name__ # foo
print B.__name__ # foo
print issubclass(B, A) # False
print issubclass(B, int) # True
```
This may be useful in frameworks for issuing warnings whenever classes with similar names or incomplete inheritance trees are defined, but I can't think of a reason beside trolling to actually change these values. Maybe David Beazley can.
Anyway, in Python 3, metaclasses also have the `__prepare__` method, which lets you evaluate the class body into a mapping other than a `dict`, thus supporting ordered attributes, overloaded attributes, and other wicked cool stuff:
```
import collections
class Metaclass(type):
@classmethod
def __prepare__(meta, name, bases, **kwds):
return collections.OrderedDict()
def __new__(meta, name, bases, attrs, **kwds):
print(list(attrs))
# Do more stuff...
class A(metaclass=Metaclass):
x = 1
y = 2
# prints ['x', 'y'] rather than ['y', 'x']
```
```
class ListDict(dict):
def __setitem__(self, key, value):
self.setdefault(key, []).append(value)
class Metaclass(type):
@classmethod
def __prepare__(meta, name, bases, **kwds):
return ListDict()
def __new__(meta, name, bases, attrs, **kwds):
print(attrs['foo'])
# Do more stuff...
class A(metaclass=Metaclass):
def foo(self):
pass
def foo(self, x):
pass
# prints [<function foo at 0x...>, <function foo at 0x...>] rather than <function foo at 0x...>
```
You might argue ordered attributes can be achieved with creation counters, and overloading can be simulated with default arguments:
```
import itertools
class Attribute(object):
_counter = itertools.count()
def __init__(self):
self._count = Attribute._counter.next()
class A(object):
x = Attribute()
y = Attribute()
A._order = sorted([(k, v) for k, v in vars(A).items() if isinstance(v, Attribute)],
key = lambda (k, v): v._count)
```
```
class A(object):
def _foo0(self):
pass
def _foo1(self, x):
pass
def foo(self, x=None):
if x is None:
return self._foo0()
else:
return self._foo1(x)
```
Besides being much more ugly, it's also less flexible: what if you want ordered literal attributes, like integers and strings? What if `None` is a valid value for `x`?
Here's a creative way to solve the first problem:
```
import sys
class Builder(object):
def __call__(self, cls):
cls._order = self.frame.f_code.co_names
return cls
def ordered():
builder = Builder()
def trace(frame, event, arg):
builder.frame = frame
sys.settrace(None)
sys.settrace(trace)
return builder
@ordered()
class A(object):
x = 1
y = 'foo'
print A._order # ['x', 'y']
```
And here's a creative way to solve the second one:
```
_undefined = object()
class A(object):
def _foo0(self):
pass
def _foo1(self, x):
pass
def foo(self, x=_undefined):
if x is _undefined:
return self._foo0()
else:
return self._foo1(x)
```
But this is much, MUCH voodoo-er than a simple metaclass (especially the first one, which really melts your brain). My point is, you look at metaclasses as unfamiliar and counter-intuitive, but you can also look at them as the next step of evolution in programming languages: you just have to adjust your mindset. After all, you could probably do everything in C, including defining a struct with function pointers and passing it as the first argument to its functions. A person seeing C++ for the first time might say, "what is this magic? Why is the compiler implicitly passing `this` to methods, but not to regular and static functions? It's better to be explicit and verbose about your arguments". But then, object-oriented programming is much more powerful once you get it; and so is this, uh... quasi-aspect-oriented programming, I guess. And once you understand metaclasses, they're actually very simple, so why not use them when convenient?
And finally, metaclasses are rad, and programming should be fun. Using standard programming constructs and design patterns all the time is boring and uninspiring, and hinders your imagination. Live a little! Here's a metametaclass, just for you.
```
class MetaMetaclass(type):
def __new__(meta, name, bases, attrs):
def __new__(meta, name, bases, attrs):
cls = type.__new__(meta, name, bases, attrs)
cls._label = 'Made in %s' % meta.__name__
return cls
attrs['__new__'] = __new__
return type.__new__(meta, name, bases, attrs)
class China(type):
__metaclass__ = MetaMetaclass
class Taiwan(type):
__metaclass__ = MetaMetaclass
class A(object):
__metaclass__ = China
class B(object):
__metaclass__ = Taiwan
print A._label # Made in China
print B._label # Made in Taiwan
```
# Edit
This is a pretty old question, but it's still getting upvotes, so I thought I'd add a link to a more comprehensive answer. If you'd like to read more about metaclasses and their uses, I've just published an article about it [here](https://medium.com/@dan.gittik/metaphysics-2036b38fa711).
[Share](https://stackoverflow.com/a/31061875 "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/31061875/edit)
Follow
Follow this answer to receive notifications
[edited Apr 23, 2020 at 8:00](https://stackoverflow.com/posts/31061875/revisions "show all edits to this post")
answered Jun 25, 2015 at 22:26
[](https://stackoverflow.com/users/1704628/dan-gittik)
[Dan Gittik](https://stackoverflow.com/users/1704628/dan-gittik)Dan Gittik
3,91033 gold badges2020 silver badges2424 bronze badges
Sign up to request clarification or add additional context in comments.
## 6 Comments
Add a comment
[](https://stackoverflow.com/users/840582/chen-a)
Chen A.
[Chen A.](https://stackoverflow.com/users/840582/chen-a)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment79736087_31061875)
That's a great answer, thanks for the time writing it and giving multiple examples
2017-09-24T11:06:21.18Z+00:00
13
Reply
- Copy link
[](https://stackoverflow.com/users/4354477/forcebru)
ForceBru
[ForceBru](https://stackoverflow.com/users/4354477/forcebru)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment88413229_31061875)
"...the advantage of metaclasses in this case is inheritance, as they work for any subclasses" - not in Python 3, I suppose? I think it works in Python 2 only because any child class inherits the `__metaclass__` attribute, but this attribute is no longer special in Python 3. Is there any way to make this "children classes are also constructed by the parent's metaclass" thing work in Python 3?
2018-06-05T13:57:36.373Z+00:00
1
Reply
- Copy link
[](https://stackoverflow.com/users/1704628/dan-gittik)
Dan Gittik
[Dan Gittik](https://stackoverflow.com/users/1704628/dan-gittik)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment88581977_31061875)
This is true for Python 3 as well, because a class B, inheriting from A, whose metaclass is M, is also a type-of M. So, when B is evaluated, M is invoked to create it, and this effectively allows you to "work on any subclasses" (of A). Having said that, Python 3.6 introduced the much simpler [`init_subclass`](https://docs.python.org/3/reference/datamodel.html#object.__init_subclass__), so now you can manipulate subclasses in a baseclass, and no longer need a metaclass for that purpose.
2018-06-10T20:38:16.17Z+00:00
2
Reply
- Copy link
[](https://stackoverflow.com/users/1061155/ospider)
ospider
[ospider](https://stackoverflow.com/users/1061155/ospider)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment104372411_31061875)
This is brilliant, I read so many blog posts on metaclasses, only this one make know the pros and cons and alternatives to metaclass.
2019-11-27T09:34:36.477Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/15288054/ryan-laursen)
Ryan Laursen
[Ryan Laursen](https://stackoverflow.com/users/15288054/ryan-laursen)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment118974847_31061875)
The "overloading" example does not work without *significantly* more overhead, an attempt at actually implementing it returns this error due to `__prepare__` being a dict of lists, which would would take significant steps to rectify: `TypeError: type __qualname__ must be a str, not list`
2021-04-29T01:48:41.217Z+00:00
0
Reply
- Copy link
Add a comment
\|
Show 1 more comment
This answer is useful
38
Save this answer.
Show activity on this post.
The purpose of metaclasses isn't to replace the class/object distinction with metaclass/class - it's to change the behaviour of class definitions (and thus their instances) in some way. Effectively it's to alter the behaviour of the class statement in ways that may be more useful for your particular domain than the default. The things I have used them for are:
- Tracking subclasses, usually to register handlers. This is handy when using a plugin style setup, where you wish to register a handler for a particular thing simply by subclassing and setting up a few class attributes. eg. suppose you write a handler for various music formats, where each class implements appropriate methods (play / get tags etc) for its type. Adding a handler for a new type becomes:
```
class Mp3File(MusicFile):
extensions = ['.mp3'] # Register this type as a handler for mp3 files
...
# Implementation of mp3 methods go here
```
The metaclass then maintains a dictionary of `{'.mp3' : MP3File, ... }` etc, and constructs an object of the appropriate type when you request a handler through a factory function.
- Changing behaviour. You may want to attach a special meaning to certain attributes, resulting in altered behaviour when they are present. For example, you may want to look for methods with the name `_get_foo` and `_set_foo` and transparently convert them to properties. As a real-world example, [here's](http://code.activestate.com/recipes/498149/) a recipe I wrote to give more C-like struct definitions. The metaclass is used to convert the declared items into a struct format string, handling inheritance etc, and produce a class capable of dealing with it.
For other real-world examples, take a look at various ORMs, like [sqlalchemy's](http://www.sqlalchemy.org/) ORM or [sqlobject](http://www.sqlobject.org/). Again, the purpose is to interpret defintions (here SQL column definitions) with a particular meaning.
[Share](https://stackoverflow.com/a/392255 "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/392255/edit)
Follow
Follow this answer to receive notifications
[edited Dec 25, 2008 at 6:06](https://stackoverflow.com/posts/392255/revisions "show all edits to this post")
[](https://stackoverflow.com/users/10661/s-lott)
[S.Lott](https://stackoverflow.com/users/10661/s-lott)
393k8383 gold badges520520 silver badges791791 bronze badges
answered Dec 24, 2008 at 21:43
[](https://stackoverflow.com/users/9493/brian)
[Brian](https://stackoverflow.com/users/9493/brian)Brian
120k2929 gold badges111111 silver badges114114 bronze badges
## 6 Comments
Add a comment
[](https://stackoverflow.com/users/28380/ali-afshar)
Ali Afshar
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219406_392255)
Well, yes, tracking subclasses. But why would you ever want that? Your example is just implicit for register\_music\_file(Mp3File, \['.mp3'\]), and the explicit way is more readable and maintainable. This is an example of the bad cases I am talking about.
2008-12-24T22:47:08.857Z+00:00
4
Reply
- Copy link
[](https://stackoverflow.com/users/28380/ali-afshar)
Ali Afshar
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219410_392255)
About the ORM case, are you talking about the class-based way of defining tables, or the metaclasses on mapped objects. Because SQLAlchemy can (rightly) map to any class (and I am assuming that it doesn't use a metaclass for that activity).
2008-12-24T22:51:43.59Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/9493/brian)
Brian
[Brian](https://stackoverflow.com/users/9493/brian)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219416_392255)
I prefer the more declarative style, rather than require extra registration methods for every subclass - better if everything is wrapped in a single location.
2008-12-24T23:10:31.68Z+00:00
12
Reply
- Copy link
[](https://stackoverflow.com/users/9493/brian)
Brian
[Brian](https://stackoverflow.com/users/9493/brian)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219418_392255)
For sqlalchemy, I'm thinking mostly of the declarative layer, so perhaps sqlobject is a better example. However the metaclasses used internally are also examples of similar reinterpretation of particular attributes to declare meaning.
2008-12-24T23:11:48.933Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/28380/ali-afshar)
Ali Afshar
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219805_392255)
Sorry one of my conmments got lost in the SO timeout scenario. I find classes for declarative almost an abomination. I know people love it, and it is accepted behaviour. But (from experience) I know it is unusable in a situation where you want to UN-declare things. Unregistering a class is *hard*.
2008-12-25T12:53:14.157Z+00:00
2
Reply
- Copy link
Add a comment
\|
Show 1 more comment
This answer is useful
29
Save this answer.
Show activity on this post.
I have a class that handles non-interactive plotting, as a frontend to Matplotlib. However, on occasion one wants to do interactive plotting. With only a couple functions I found that I was able to increment the figure count, call draw manually, etc, but I needed to do these before and after every plotting call. So to create both an interactive plotting wrapper and an offscreen plotting wrapper, I found it was more efficient to do this via metaclasses, wrapping the appropriate methods, than to do something like:
```
class PlottingInteractive:
add_slice = wrap_pylab_newplot(add_slice)
```
This method doesn't keep up with API changes and so on, but one that iterates over the class attributes in `__init__` before re-setting the class attributes is more efficient and keeps things up to date:
```
class _Interactify(type):
def __init__(cls, name, bases, d):
super(_Interactify, cls).__init__(name, bases, d)
for base in bases:
for attrname in dir(base):
if attrname in d: continue # If overridden, don't reset
attr = getattr(cls, attrname)
if type(attr) == types.MethodType:
if attrname.startswith("add_"):
setattr(cls, attrname, wrap_pylab_newplot(attr))
elif attrname.startswith("set_"):
setattr(cls, attrname, wrap_pylab_show(attr))
```
Of course, there might be better ways to do this, but I've found this to be effective. Of course, this could also be done in `__new__` or `__init__`, but this was the solution I found the most straightforward.
[Share](https://stackoverflow.com/a/393368 "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/393368/edit)
Follow
Follow this answer to receive notifications
[edited Dec 26, 2008 at 18:42](https://stackoverflow.com/posts/393368/revisions "show all edits to this post")
[](https://stackoverflow.com/users/28380/ali-afshar)
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
41\.8k1212 gold badges9797 silver badges111111 bronze badges
answered Dec 26, 2008 at 1:35
[](https://stackoverflow.com/users/49135/matt)
[Matt](https://stackoverflow.com/users/49135/matt)Matt
74755 silver badges1010 bronze badges
## Comments
Add a comment
This answer is useful
22
Save this answer.
Show activity on this post.
Let's start with Tim Peter's classic quote:
> Metaclasses are deeper magic than 99% of users should ever worry about. 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). Tim Peters (c.l.p post 2002-12-22)
Having said that, I have (periodically) run across true uses of metaclasses. The one that comes to mind is in Django where all of your models inherit from models.Model. models.Model, in turn, does some serious magic to wrap your DB models with Django's ORM goodness. That magic happens by way of metaclasses. It creates all manner of exception classes, manager classes, etc. etc.
See django/db/models/base.py, class ModelBase() for the beginning of the story.
[Share](https://stackoverflow.com/a/392442 "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/392442/edit)
Follow
Follow this answer to receive notifications
answered Dec 25, 2008 at 2:23
[](https://stackoverflow.com/users/17017/peter-rowell)
[Peter Rowell](https://stackoverflow.com/users/17017/peter-rowell)Peter Rowell
17\.8k22 gold badges5252 silver badges6565 bronze badges
## 2 Comments
Add a comment
[](https://stackoverflow.com/users/28380/ali-afshar)
Ali Afshar
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219798_392442)
Well, yes, I see the point. I don't wonder "how" or "why" to use metaclasses, I wonder the "who" and the "what". ORMs are a common case here I see. Unfortunately Django's ORM is pretty poor compared to SQLAlchemy which has less magic. Magic is bad, and metaclasses are really not necessary for this.
2008-12-25T12:40:57.6Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/216356/noctis-skytower)
Noctis Skytower
[Noctis Skytower](https://stackoverflow.com/users/216356/noctis-skytower)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment24430622_392442)
Having read Tim Peters' quote in the past, time has showed that his statement is rather unhelpful. Not until researching Python metaclasses here on StackOverflow did it become apparent how to even implement them. After forcing myself to learn how to write and use metaclasses, their abilities astonished me and gave me a much better understanding of how Python really works. Classes can provide reusable code, and metaclasses can provide reusable enhancements for those classes.
2013-06-04T17:21:16.43Z+00:00
14
Reply
- Copy link
This answer is useful
9
Save this answer.
Show activity on this post.
The only legitimate use-case of a metaclass is to keep other nosy developers from touching your code. Once a nosy developer masters metaclasses and starts poking around with yours, throw in another level or two to keep them out. If that doesn't work, start using `type.__new__` or perhaps some scheme using a recursive metaclass.
(written tongue in cheek, but I've seen this kind of obfuscation done. Django is a perfect example)
[Share](https://stackoverflow.com/a/5330521 "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/5330521/edit)
Follow
Follow this answer to receive notifications
[edited Dec 20, 2016 at 3:18](https://stackoverflow.com/posts/5330521/revisions "show all edits to this post")
[](https://stackoverflow.com/users/296460/shuttle87)
[shuttle87](https://stackoverflow.com/users/296460/shuttle87)
16k1212 gold badges8080 silver badges107107 bronze badges
answered Mar 16, 2011 at 19:13
[](https://stackoverflow.com/users/48814/mike-a)
[Mike A](https://stackoverflow.com/users/48814/mike-a)Mike A
1,3151212 silver badges1414 bronze badges
## 1 Comment
Add a comment
[](https://stackoverflow.com/users/28380/ali-afshar)
Ali Afshar
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment6041122_5330521)
I'm not sure the motivation was the same in Django.
2011-03-18T07:21:07.29Z+00:00
9
Reply
- Copy link
This answer is useful
9
Save this answer.
Show activity on this post.
A reasonable pattern of metaclass use is doing something once when a class is defined rather than repeatedly whenever the same class is instantiated.
When multiple classes share the same special behaviour, repeating `__metaclass__=X` is obviously better than repeating the special purpose code and/or introducing ad-hoc shared superclasses.
But even with only one special class and no foreseeable extension, `__new__` and `__init__` of a metaclass are a cleaner way to initialize class variables or other global data than intermixing special-purpose code and normal `def` and `class` statements in the class definition body.
[Share](https://stackoverflow.com/a/7057480 "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/7057480/edit)
Follow
Follow this answer to receive notifications
[edited Feb 15, 2018 at 3:15](https://stackoverflow.com/posts/7057480/revisions "show all edits to this post")
[](https://stackoverflow.com/users/355230/martineau)
[martineau](https://stackoverflow.com/users/355230/martineau)
124k2929 gold badges180180 silver badges318318 bronze badges
answered Aug 14, 2011 at 14:49
[](https://stackoverflow.com/users/412090/user412090)
[user412090](https://stackoverflow.com/users/412090/user412090)user412090
35644 silver badges77 bronze badges
## Comments
Add a comment
This answer is useful
8
Save this answer.
Show activity on this post.
Metaclasses can be handy for construction of Domain Specific Languages in Python. Concrete examples are Django, SQLObject 's declarative syntax of database schemata.
A basic example from [A Conservative Metaclass](http://blog.ianbicking.org/a-conservative-metaclass.html) by Ian Bicking:
> The metaclasses I've used have been primarily to support a sort of declarative style of programming. For instance, consider a validation schema:
```
class Registration(schema.Schema):
first_name = validators.String(notEmpty=True)
last_name = validators.String(notEmpty=True)
mi = validators.MaxLength(1)
class Numbers(foreach.ForEach):
class Number(schema.Schema):
type = validators.OneOf(['home', 'work'])
phone_number = validators.PhoneNumber()
```
Some other techniques: [Ingredients for Building a DSL in Python](http://web.archive.org/web/20091229094610/http://media.brianbeck.com/files/Python_DSLs_I.pdf) (pdf).
Edit (by Ali): An example of doing this using collections and instances is what I would prefer. The important fact is the instances, which give you more power, and eliminate reason to use metaclasses. Further worth noting that your example uses a mixture of classes and instances, which is surely an indication that you can't just do it all with metaclasses. And creates a truly non-uniform way of doing it.
```
number_validator = [
v.OneOf('type', ['home', 'work']),
v.PhoneNumber('phone_number'),
]
validators = [
v.String('first_name', notEmpty=True),
v.String('last_name', notEmpty=True),
v.MaxLength('mi', 1),
v.ForEach([number_validator,])
]
```
It's not perfect, but already there is almost zero magic, no need for metaclasses, and improved uniformity.
[Share](https://stackoverflow.com/a/392308 "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/392308/edit)
Follow
Follow this answer to receive notifications
[edited Jan 9, 2013 at 18:26](https://stackoverflow.com/posts/392308/revisions "show all edits to this post")
[](https://stackoverflow.com/users/309233/tripp-lilley)
[Tripp Lilley](https://stackoverflow.com/users/309233/tripp-lilley)
1,6531616 silver badges2121 bronze badges
answered Dec 24, 2008 at 22:54
[](https://stackoverflow.com/users/4279/jfs)
[jfs](https://stackoverflow.com/users/4279/jfs)jfs
417k210210 gold badges1k1k silver badges1\.7k1\.7k bronze badges
## 5 Comments
Add a comment
[](https://stackoverflow.com/users/28380/ali-afshar)
Ali Afshar
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219442_392308)
Thanks for this. This is a very good example of a use-case I think is unnecessary, ugly, and unmanagemable, which would be simpler based on a simple collection instance (with nested collections as required).
2008-12-24T23:57:51.54Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/4279/jfs)
jfs
[jfs](https://stackoverflow.com/users/4279/jfs)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219504_392308)
@Ali A: you are welcome to provide a concrete example of side-by-side comparision between declarative syntax via metaclasses and an approach based on simple collection instance.
2008-12-25T02:00:31.2Z+00:00
1
Reply
- Copy link
[](https://stackoverflow.com/users/4279/jfs)
jfs
[jfs](https://stackoverflow.com/users/4279/jfs)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219696_392308)
@Ali A: you may edit my answer inplace to add a collection style example.
2008-12-25T07:59:17.933Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/28380/ali-afshar)
Ali Afshar
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219767_392308)
Ok done that. Sorry am in a bit of a hurry today, but will try to answer any queries later/tomorrow. Happy Holidays\!
2008-12-25T11:15:43.713Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/309412/lie-ryan)
Lie Ryan
[Lie Ryan](https://stackoverflow.com/users/309412/lie-ryan)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment13844683_392308)
The second example is ugly as you had to tie the validator instance with their name. A slightly better way of doing it is to use a dictionary instead of a list, but then, in python classes are just syntax sugar for dictionary, so why not use classes? You get free name validation as well because python babes cannot contain spaces or special characters that a string could.
2012-05-20T06:37:29.157Z+00:00
3
Reply
- Copy link
Add a comment
This answer is useful
7
Save this answer.
Show activity on this post.
I was thinking the same thing just yesterday and completely agree. The complications in the code caused by attempts to make it more declarative generally make the codebase harder to maintain, harder to read and less pythonic in my opinion. It also normally requires a lot of copy.copy()ing (to maintain inheritance and to copy from class to instance) and means you have to look in many places to see whats going on (always looking from metaclass up) which goes against the python grain also. I have been picking through formencode and sqlalchemy code to see if such a declarative style was worth it and its clearly not. Such style should be left to descriptors (such as property and methods) and immutable data. Ruby has better support for such declarative styles and I am glad the core python language is not going down that route.
I can see their use for debugging, add a metaclass to all your base classes to get richer info. I also see their use only in (very) large projects to get rid of some boilerplate code (but at the loss of clarity). sqlalchemy for [example](http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/lib/sqlalchemy/sql/visitors.py) does use them elsewhere, to add a particular custom method to all subclasses based on an attribute value in their class definition e.g a toy example
```
class test(baseclass_with_metaclass):
method_maker_value = "hello"
```
could have a metaclass that generated a method in that class with special properties based on "hello" (say a method that added "hello" to the end of a string). It could be good for maintainability to make sure you did not have to write a method in every subclass you make instead all you have to define is method\_maker\_value.
The need for this is so rare though and only cuts down on a bit of typing that its not really worth considering unless you have a large enough codebase.
[Share](https://stackoverflow.com/a/395751 "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/395751/edit)
Follow
Follow this answer to receive notifications
[edited Dec 28, 2008 at 3:32](https://stackoverflow.com/posts/395751/revisions "show all edits to this post")
answered Dec 28, 2008 at 3:20
[](https://stackoverflow.com/users/20842/david-raznick)
[David Raznick](https://stackoverflow.com/users/20842/david-raznick)David Raznick
18\.6k22 gold badges3838 silver badges2727 bronze badges
## Comments
Add a comment
This answer is useful
5
Save this answer.
Show activity on this post.
The only time I used metaclasses in Python was when writing a wrapper for the Flickr API.
My goal was to scrape [flickr's api site](http://www.flickr.com/services/api/) and dynamically generate a complete class hierarchy to allow API access using Python objects:
```
# Both the photo type and the flickr.photos.search API method
# are generated at "run-time"
for photo in flickr.photos.search(text=balloons):
print photo.description
```
So in that example, because I generated the entire Python Flickr API from the website, I really don't know the class definitions at runtime. Being able to dynamically generate types was very useful.
[Share](https://stackoverflow.com/a/392232 "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/392232/edit)
Follow
Follow this answer to receive notifications
answered Dec 24, 2008 at 21:19
[](https://stackoverflow.com/users/43089/kenan-banks)
[Kenan Banks](https://stackoverflow.com/users/43089/kenan-banks)Kenan Banks
213k3636 gold badges160160 silver badges176176 bronze badges
## 2 Comments
Add a comment
[](https://stackoverflow.com/users/28380/ali-afshar)
Ali Afshar
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219412_392232)
You can dynamically generate types without using metaclasses. \>\>\> help(type)
2008-12-24T22:52:44.62Z+00:00
4
Reply
- Copy link
[](https://stackoverflow.com/users/1875565/veky)
Veky
[Veky](https://stackoverflow.com/users/1875565/veky)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment47104368_392232)
Even if you're not aware of it, you *are* using metaclasses then. type is a metaclass, in fact the most common one. :-)
2015-04-06T12:42:19.687Z+00:00
10
Reply
- Copy link
This answer is useful
5
Save this answer.
Show activity on this post.
Metaclasses aren't replacing programming! They're just a trick which can automate or make more elegant some tasks. A good example of this is [Pygments](http://pygments.org/) syntax highlighting library. It has a class called `RegexLexer` which lets the user define a set of lexing rules as regular expressions on a class. A metaclass is used to turn the definitions into a useful parser.
They're like salt; it's easy to use too much.
[Share](https://stackoverflow.com/a/392278 "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/392278/edit)
Follow
Follow this answer to receive notifications
answered Dec 24, 2008 at 22:15
[](https://stackoverflow.com/users/33795/benjamin-peterson)
[Benjamin Peterson](https://stackoverflow.com/users/33795/benjamin-peterson)Benjamin Peterson
20\.8k66 gold badges3535 silver badges4343 bronze badges
## 2 Comments
Add a comment
[](https://stackoverflow.com/users/28380/ali-afshar)
Ali Afshar
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219402_392278)
Well, in my opinion, that Pygments case is just unnecessary. Why not just have a plain collection like a dict, why force a class to do this?
2008-12-24T22:42:49.04Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/33795/benjamin-peterson)
Benjamin Peterson
[Benjamin Peterson](https://stackoverflow.com/users/33795/benjamin-peterson)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment221468_392278)
Because a class nice encapulates the idea of Lexer and has other useful methods like guess\_filename(), etc.
2008-12-27T03:54:51.043Z+00:00
4
Reply
- Copy link
This answer is useful
4
Save this answer.
Show activity on this post.
Some GUI libraries have trouble when multiple threads try to interact with them. `tkinter` is one such example; and while one can explicitly handle the problem with events and queues, it can be far simpler to use the library in a manner that ignores the problem altogether. Behold -- the magic of metaclasses.
Being able to dynamically rewrite an entire library seamlessly so that it works properly as expected in a multithreaded application can be extremely helpful in some circumstances. The [safetkinter](http://code.activestate.com/recipes/578153/) module does that with the help of a metaclass provided by the [threadbox](http://code.activestate.com/recipes/578152/) module -- events and queues not needed.
One neat aspect of `threadbox` is that it does not care what class it clones. It provides an example of how all base classes can be touched by a metaclass if needed. A further benefit that comes with metaclasses is that they run on inheriting classes as well. Programs that write themselves -- why not?
[Share](https://stackoverflow.com/a/16925938 "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/16925938/edit)
Follow
Follow this answer to receive notifications
answered Jun 4, 2013 at 19:29
[](https://stackoverflow.com/users/216356/noctis-skytower)
[Noctis Skytower](https://stackoverflow.com/users/216356/noctis-skytower)Noctis Skytower
22\.1k1616 gold badges8686 silver badges122122 bronze badges
## Comments
Add a comment
This answer is useful
4
Save this answer.
Show activity on this post.
You never absolutely *need* to use a metaclass, since you can always construct a class that does what you want using inheritance or aggregation of the class you want to modify.
That said, it can be very handy in Smalltalk and Ruby to be able to modify an existing class, but Python doesn't like to do that directly.
There's an excellent [DeveloperWorks article](https://web.archive.org/web/20130716222859/http://www.ibm.com:80/developerworks/linux/library/l-pymeta/index.html) on metaclassing in Python that might help. The [Wikipedia article](http://en.wikipedia.org/wiki/Metaclass) is also pretty good.
[Share](https://stackoverflow.com/a/392230 "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/392230/edit)
Follow
Follow this answer to receive notifications
[edited Feb 11, 2020 at 14:54](https://stackoverflow.com/posts/392230/revisions "show all edits to this post")
[](https://stackoverflow.com/users/73103/eugene-morozov)
[Eugene Morozov](https://stackoverflow.com/users/73103/eugene-morozov)
16k33 gold badges2828 silver badges3434 bronze badges
answered Dec 24, 2008 at 21:17
[](https://stackoverflow.com/users/35092/charlie-martin)
[Charlie Martin](https://stackoverflow.com/users/35092/charlie-martin)Charlie Martin
113k2727 gold badges197197 silver badges267267 bronze badges
## 2 Comments
Add a comment
[](https://stackoverflow.com/users/652722/tyler-crompton)
Tyler Crompton
[Tyler Crompton](https://stackoverflow.com/users/652722/tyler-crompton)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment61487913_392230)
You also don't need objects to do object oriented programming—you could do it with first class functions. So you don't *need* to use objects. But they're there for convenience. So I'm not sure what point you're trying to make in the first paragraph.
2016-05-01T11:31:08.557Z+00:00
1
Reply
- Copy link
[](https://stackoverflow.com/users/35092/charlie-martin)
Charlie Martin
[Charlie Martin](https://stackoverflow.com/users/35092/charlie-martin)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment61494220_392230)
Look back at the question.
2016-05-01T16:54:10.253Z+00:00
1
Reply
- Copy link
This answer is useful
3
Save this answer.
Show activity on this post.
The way I used metaclasses was to provide some attributes to classes. Take for example:
```
class NameClass(type):
def __init__(cls, *args, **kwargs):
type.__init__(cls, *args, **kwargs)
cls.name = cls.__name__
```
will put the *name* attribute on every class that will have the metaclass set to point to NameClass.
[Share](https://stackoverflow.com/a/392767 "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/392767/edit)
Follow
Follow this answer to receive notifications
answered Dec 25, 2008 at 11:47
[](https://stackoverflow.com/users/49032/hyperboreean)
[hyperboreean](https://stackoverflow.com/users/49032/hyperboreean)hyperboreean
8,3431313 gold badges6767 silver badges9898 bronze badges
## 1 Comment
Add a comment
[](https://stackoverflow.com/users/28380/ali-afshar)
Ali Afshar
[Ali Afshar](https://stackoverflow.com/users/28380/ali-afshar)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment219807_392767)
Yes, this works. You could use a superclass also, which is at least explicit, and followable in code. Out of interest, what did you use this for?
2008-12-25T12:55:24.95Z+00:00
5
Reply
- Copy link
This answer is useful
2
Save this answer.
Show activity on this post.
This is a minor use, but... one thing I've found metaclasses useful for is to invoke a function whenever a subclass is created. I codified this into a metaclass which looks for an `__initsubclass__` attribute: whenever a subclass is created, all parent classes which define that method are invoked with `__initsubclass__(cls, subcls)`. This allows creation of a parent class which then registers all subclasses with some global registry, runs invariant checks on subclasses whenever they are defined, perform late-binding operations, etc... all without have to manually call functions *or* to create custom metaclasses that perform each of these separate duties.
Mind you, I've slowly come to realize the implicit magicalness of this behavior is somewhat undesirable, since it's unexpected if looking at a class definition out of context... and so I've moved away from using that solution for anything serious besides initializing a `__super` attribute for each class and instance.
[Share](https://stackoverflow.com/a/7058179 "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/7058179/edit)
Follow
Follow this answer to receive notifications
answered Aug 14, 2011 at 16:44
[](https://stackoverflow.com/users/681277/eli-collins)
[Eli Collins](https://stackoverflow.com/users/681277/eli-collins)Eli Collins
8,57322 gold badges3636 silver badges3838 bronze badges
## Comments
Add a comment
This answer is useful
1
Save this answer.
Show activity on this post.
I recently had to use a metaclass to help declaratively define an SQLAlchemy model around a database table populated with U.S. Census data from <http://census.ire.org/data/bulkdata.html>
IRE provides [database shells](https://github.com/ireapps/census/tree/master/tools/sql/ire_export) for the census data tables, which create integer columns following a naming convention from the Census Bureau of p012015, p012016, p012017, etc.
I wanted to a) be able to access these columns using a `model_instance.p012017` syntax, b) be fairly explicit about what I was doing and c) not have to explicitly define dozens of fields on the model, so I subclassed SQLAlchemy's `DeclarativeMeta` to iterate through a range of the columns and automatically create model fields corresponding to the columns:
```
from sqlalchemy.ext.declarative.api import DeclarativeMeta
class CensusTableMeta(DeclarativeMeta):
def __init__(cls, classname, bases, dict_):
table = 'p012'
for i in range(1, 49):
fname = "%s%03d" % (table, i)
dict_[fname] = Column(Integer)
setattr(cls, fname, dict_[fname])
super(CensusTableMeta, cls).__init__(classname, bases, dict_)
```
I could then use this metaclass for my model definition and access the automatically enumerated fields on the model:
```
CensusTableBase = declarative_base(metaclass=CensusTableMeta)
class P12Tract(CensusTableBase):
__tablename__ = 'ire_p12'
geoid = Column(String(12), primary_key=True)
@property
def male_under_5(self):
return self.p012003
...
```
[Share](https://stackoverflow.com/a/19865575 "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/19865575/edit)
Follow
Follow this answer to receive notifications
answered Nov 8, 2013 at 17:59
[](https://stackoverflow.com/users/386210/geoffrey-hing)
[Geoffrey Hing](https://stackoverflow.com/users/386210/geoffrey-hing)Geoffrey Hing
1,82522 gold badges1919 silver badges2323 bronze badges
## Comments
Add a comment
This answer is useful
1
Save this answer.
Show activity on this post.
There seems to be a legitimate use described [here](http://www.jesshamrick.com/2013/04/17/rewriting-python-docstrings-with-a-metaclass/) - Rewriting Python Docstrings with a Metaclass.
[Share](https://stackoverflow.com/a/23853525 "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/23853525/edit)
Follow
Follow this answer to receive notifications
answered May 25, 2014 at 8:44
[](https://stackoverflow.com/users/2170009/mistermarko)
[mistermarko](https://stackoverflow.com/users/2170009/mistermarko)mistermarko
30511 gold badge44 silver badges2020 bronze badges
## Comments
Add a comment
This answer is useful
1
Save this answer.
Show activity on this post.
[Pydantic](https://pydantic-docs.helpmanual.io/) is a library for data validation and settings management that enforces type hints at runtime and provides user friendly errors when data is invalid. It makes use of metaclasses for its BaseModel and for number range validation.
At work I encountered some code that had a process that had several stages defined by classes. The ordering of these steps was controlled by metaclasses that added the steps to a list as the classes were defined. This was thrown out and the order was set by adding them to a list.
[Share](https://stackoverflow.com/a/67594380 "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/67594380/edit)
Follow
Follow this answer to receive notifications
answered May 18, 2021 at 21:53
[](https://stackoverflow.com/users/223960/brian-c)
[Brian C.](https://stackoverflow.com/users/223960/brian-c)Brian C.
8,15055 gold badges4141 silver badges5050 bronze badges
## Comments
Add a comment
This answer is useful
0
Save this answer.
Show activity on this post.
I had to use them once for a binary parser to make it easier to use. You define a message class with attributes of the fields present on the wire. They needed to be ordered in the way they were declared to construct the final wire format from it. You can do that with metaclasses, if you use an ordered namespace dict. In fact, its in the examples for Metaclasses:
<https://docs.python.org/3/reference/datamodel.html#metaclass-example>
But in general: Very carefully evaluate, if you really really need the added complexity of metaclasses.
[Share](https://stackoverflow.com/a/39292817 "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/39292817/edit)
Follow
Follow this answer to receive notifications
answered Sep 2, 2016 at 12:47
[](https://stackoverflow.com/users/190001/geef)
[GeeF](https://stackoverflow.com/users/190001/geef)GeeF
71722 gold badges88 silver badges1717 bronze badges
## Comments
Add a comment
This answer is useful
0
Save this answer.
Show activity on this post.
the answer from @Dan Gittik is cool
the examples at the end could clarify many things,I changed it to python 3 and give some explanation:
```
class MetaMetaclass(type):
def __new__(meta, name, bases, attrs):
def __new__(meta, name, bases, attrs):
cls = type.__new__(meta, name, bases, attrs)
cls._label = 'Made in %s' % meta.__name__
return cls
attrs['__new__'] = __new__
return type.__new__(meta, name, bases, attrs)
#China is metaclass and it's __new__ method would be changed by MetaMetaclass(metaclass)
class China(MetaMetaclass, metaclass=MetaMetaclass):
__metaclass__ = MetaMetaclass
#Taiwan is metaclass and it's __new__ method would be changed by MetaMetaclass(metaclass)
class Taiwan(MetaMetaclass, metaclass=MetaMetaclass):
__metaclass__ = MetaMetaclass
#A is a normal class and it's __new__ method would be changed by China(metaclass)
class A(metaclass=China):
__metaclass__ = China
#B is a normal class and it's __new__ method would be changed by Taiwan(metaclass)
class B(metaclass=Taiwan):
__metaclass__ = Taiwan
print(A._label) # Made in China
print(B._label) # Made in Taiwan
```
- everything is object,so class is object
- class object is created by metaclass
- all class inheritted from type is metaclass
- metaclass could control class creating
- metaclass could control metaclass creating too(so it could loop for ever)
- this's metaprograming...you could control the type system at running time
- again,everything is object,this's a uniform system,type create type,and type create instance
[Share](https://stackoverflow.com/a/57163747 "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/57163747/edit)
Follow
Follow this answer to receive notifications
answered Jul 23, 2019 at 11:58
[](https://stackoverflow.com/users/6349915/foolcage)
[foolcage](https://stackoverflow.com/users/6349915/foolcage)foolcage
1,10477 silver badges99 bronze badges
## Comments
Add a comment
This answer is useful
0
Save this answer.
Show activity on this post.
Another use case is when you want to be able to modify class-level attributes and be sure that it only affects the object at hand. In practice, this implies "merging" the phases of metaclasses and classes instantiations, thus leading you to deal only with class instances of their own (unique) kind.
I also had to do that when (for concerns of [readibility](https://zen-of-python.info/readability-counts.html) and [polymorphism](https://stackify.com/oop-concept-polymorphism/)) we wanted to ***dynamically define*** [`property`](https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work)s which returned values (may) result from calculations based on (often changing) instance-level attributes, which *can only be done at the class level*, *i.e.* after the metaclass instantiation and before the class instantiation.
[Share](https://stackoverflow.com/a/57539860 "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/57539860/edit)
Follow
Follow this answer to receive notifications
[edited Aug 19, 2019 at 10:58](https://stackoverflow.com/posts/57539860/revisions "show all edits to this post")
answered Aug 17, 2019 at 20:53
[](https://stackoverflow.com/users/4194079/keepalive)
[keepAlive](https://stackoverflow.com/users/4194079/keepalive)keepAlive
6,70555 gold badges2828 silver badges4343 bronze badges
## Comments
Add a comment
This answer is useful
0
Save this answer.
Show activity on this post.
I know this is an old question But here is a use case that is really invaluable if wanting to create only a single instance of a class based on the parameters passed to the constructor.
Instance singletons I use this code for creating a singleton instance of a device on a Z-Wave network. No matter how many times I create an instance if the same values are passed to the constructor if an instance with the exact same values exists then that is what gets returned.
```
import inspect
class SingletonMeta(type):
# only here to make IDE happy
_instances = {}
def __init__(cls, name, bases, dct):
super(SingletonMeta, cls).__init__(name, bases, dct)
cls._instances = {}
def __call__(cls, *args, **kwargs):
sig = inspect.signature(cls.__init__)
keywords = {}
for i, param in enumerate(list(sig.parameters.values())[1:]):
if len(args) > i:
keywords[param.name] = args[i]
elif param.name not in kwargs and param.default != param.empty:
keywords[param.name] = param.default
elif param.name in kwargs:
keywords[param.name] = kwargs[param.name]
key = []
for k in sorted(list(keywords.keys())):
key.append(keywords[k])
key = tuple(key)
if key not in cls._instances:
cls._instances[key] = (
super(SingletonMeta, cls).__call__(*args, **kwargs)
)
return cls._instances[key]
class Test1(metaclass=SingletonMeta):
def __init__(self, param1, param2='test'):
pass
class Test2(metaclass=SingletonMeta):
def __init__(self, param3='test1', param4='test2'):
pass
test1 = Test1('test1')
test2 = Test1('test1', 'test2')
test3 = Test1('test1', 'test')
test4 = Test2()
test5 = Test2(param4='test1')
test6 = Test2('test2', 'test1')
test7 = Test2('test1')
print('test1 == test2:', test1 == test2)
print('test2 == test3:', test2 == test3)
print('test1 == test3:', test1 == test3)
print('test4 == test2:', test4 == test2)
print('test7 == test3:', test7 == test3)
print('test6 == test4:', test6 == test4)
print('test7 == test4:', test7 == test4)
print('test5 == test6:', test5 == test6)
print('number of Test1 instances:', len(Test1._instances))
print('number of Test2 instances:', len(Test2._instances))
```
output
```
test1 == test2: False
test2 == test3: False
test1 == test3: True
test4 == test2: False
test7 == test3: False
test6 == test4: False
test7 == test4: True
test5 == test6: False
number of Test1 instances: 2
number of Test2 instances: 3
```
Now someone might say it can be done without the use of a metaclass and I know it can be done if the \_\_init\_\_ method is decorated. I do not know of another way to do it. The code below while it will return a similiar instance that contains all of the same data it is not a singleton instance, a new instance gets created. Because it creates a new instance with the same data there wuld need to be additional steps taken to check equality of instances. I n the end it consumes more memory then using a metaclass and with the meta class no additional steps need to be taken to check equality.
```
class Singleton(object):
_instances = {}
def __init__(self, param1, param2='test'):
key = (param1, param2)
if key in self._instances:
self.__dict__.update(self._instances[key].__dict__)
else:
self.param1 = param1
self.param2 = param2
self._instances[key] = self
test1 = Singleton('test1', 'test2')
test2 = Singleton('test')
test3 = Singleton('test', 'test')
print('test1 == test2:', test1 == test2)
print('test2 == test3:', test2 == test3)
print('test1 == test3:', test1 == test3)
print('test1 params', test1.param1, test1.param2)
print('test2 params', test2.param1, test2.param2)
print('test3 params', test3.param1, test3.param2)
print('number of Singleton instances:', len(Singleton._instances))
```
output
```
test1 == test2: False
test2 == test3: False
test1 == test3: False
test1 params test1 test2
test2 params test test
test3 params test test
number of Singleton instances: 2
```
The metaclass approach is really nice to use if needing to check for the removal or addition of a new instance as well.
```
import inspect
class SingletonMeta(type):
# only here to make IDE happy
_instances = {}
def __init__(cls, name, bases, dct):
super(SingletonMeta, cls).__init__(name, bases, dct)
cls._instances = {}
def __call__(cls, *args, **kwargs):
sig = inspect.signature(cls.__init__)
keywords = {}
for i, param in enumerate(list(sig.parameters.values())[1:]):
if len(args) > i:
keywords[param.name] = args[i]
elif param.name not in kwargs and param.default != param.empty:
keywords[param.name] = param.default
elif param.name in kwargs:
keywords[param.name] = kwargs[param.name]
key = []
for k in sorted(list(keywords.keys())):
key.append(keywords[k])
key = tuple(key)
if key not in cls._instances:
cls._instances[key] = (
super(SingletonMeta, cls).__call__(*args, **kwargs)
)
return cls._instances[key]
class Test(metaclass=SingletonMeta):
def __init__(self, param1, param2='test'):
pass
instances = []
instances.append(Test('test1', 'test2'))
instances.append(Test('test1', 'test'))
print('number of instances:', len(instances))
instance = Test('test2', 'test3')
if instance not in instances:
instances.append(instance)
instance = Test('test1', 'test2')
if instance not in instances:
instances.append(instance)
print('number of instances:', len(instances))
```
output
```
number of instances: 2
number of instances: 3
```
Here is a way to remove an instance that has been created after the instance is no longer in use.
```
import inspect
import weakref
class SingletonMeta(type):
# only here to make IDE happy
_instances = {}
def __init__(cls, name, bases, dct):
super(SingletonMeta, cls).__init__(name, bases, dct)
def remove_instance(c, ref):
for k, v in list(c._instances.items())[:]:
if v == ref:
del cls._instances[k]
break
cls.remove_instance = classmethod(remove_instance)
cls._instances = {}
def __call__(cls, *args, **kwargs):
sig = inspect.signature(cls.__init__)
keywords = {}
for i, param in enumerate(list(sig.parameters.values())[1:]):
if len(args) > i:
keywords[param.name] = args[i]
elif param.name not in kwargs and param.default != param.empty:
keywords[param.name] = param.default
elif param.name in kwargs:
keywords[param.name] = kwargs[param.name]
key = []
for k in sorted(list(keywords.keys())):
key.append(keywords[k])
key = tuple(key)
if key not in cls._instances:
instance = super(SingletonMeta, cls).__call__(*args, **kwargs)
cls._instances[key] = weakref.ref(
instance,
instance.remove_instance
)
return cls._instances[key]()
class Test1(metaclass=SingletonMeta):
def __init__(self, param1, param2='test'):
pass
class Test2(metaclass=SingletonMeta):
def __init__(self, param3='test1', param4='test2'):
pass
test1 = Test1('test1')
test2 = Test1('test1', 'test2')
test3 = Test1('test1', 'test')
test4 = Test2()
test5 = Test2(param4='test1')
test6 = Test2('test2', 'test1')
test7 = Test2('test1')
print('test1 == test2:', test1 == test2)
print('test2 == test3:', test2 == test3)
print('test1 == test3:', test1 == test3)
print('test4 == test2:', test4 == test2)
print('test7 == test3:', test7 == test3)
print('test6 == test4:', test6 == test4)
print('test7 == test4:', test7 == test4)
print('test5 == test6:', test5 == test6)
print('number of Test1 instances:', len(Test1._instances))
print('number of Test2 instances:', len(Test2._instances))
print()
del test1
del test5
del test6
print('number of Test1 instances:', len(Test1._instances))
print('number of Test2 instances:', len(Test2._instances))
```
output
```
test1 == test2: False
test2 == test3: False
test1 == test3: True
test4 == test2: False
test7 == test3: False
test6 == test4: False
test7 == test4: True
test5 == test6: False
number of Test1 instances: 2
number of Test2 instances: 3
number of Test1 instances: 2
number of Test2 instances: 1
```
if you look at the output you will notice that the number of Test1 instances has not changed. That is because test1 and test3 are the same instance and I only deleted test1 so there is still a reference to the test1 instance in the code and as a result of that the test1 instance does not get removed.
Another nice feature of this is if the instance uses only the supplied parameters to do whatever it is tasked to do then you can use the metaclass to facilitate remote creations of the instance either on a different computer entirely or in a different process on the same machine. the parameters can simply be passed over a socket or a named pipe and a replica of the class can be created on the receiving end.
[Share](https://stackoverflow.com/a/70046930 "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/70046930/edit)
Follow
Follow this answer to receive notifications
answered Nov 20, 2021 at 14:42
user17464605user17464605
## 2 Comments
Add a comment
[](https://stackoverflow.com/users/43839/tom-swirly)
Tom Swirly
[Tom Swirly](https://stackoverflow.com/users/43839/tom-swirly)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment133777816_70046930)
"No matter how many times I create an instance if the same values are passed to the constructor if an instance with the exact same values exists then that is what gets returned." The classic way to do this is by implementing `__new__` and returning an instance without called `__int__`, if it exists.
2023-03-25T11:34:32.887Z+00:00
1
Reply
- Copy link
[](https://stackoverflow.com/users/6695608/rohit)
Rohit
[Rohit](https://stackoverflow.com/users/6695608/rohit)
[Over a year ago](https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses#comment138905993_70046930)
While one can use metaclass for implementing a Singleton, its relatively eaiser and cleaner to do this by overriding `__new__` method on the class.
2024-07-23T19:46:55.027Z+00:00
0
Reply
- Copy link
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'")
- [metaclass](https://stackoverflow.com/questions/tagged/metaclass "show questions tagged 'metaclass'")
See similar questions with these tags.
- The Overflow Blog
- [Context is king for secure, AI-generated code](https://stackoverflow.blog/2025/10/07/context-is-king-for-secure-ai-generated-code/?cb=1)
- [A new look for comments](https://stackoverflow.blog/2025/10/08/a-new-look-for-comments/?cb=1)
- Featured on Meta
- [Please welcome V2Blast back to the Community Team\!](https://meta.stackexchange.com/questions/412987/please-welcome-v2blast-back-to-the-community-team?cb=1)
- [A First Look: Stack Overflow Redesign](https://meta.stackexchange.com/questions/412992/a-first-look-stack-overflow-redesign?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)
- [Exploring new types of questions on Stack Overflow](https://meta.stackoverflow.com/questions/435121/exploring-new-types-of-questions-on-stack-overflow?cb=1)
Community activity
Last 1 hr
- Users online activity
21006 users online
- 21 questions
- 25 answers
- 106 comments
- 413 upvotes
Popular tags
[c++](https://stackoverflow.com/questions/tagged/c++)[java](https://stackoverflow.com/questions/tagged/java)[javascript](https://stackoverflow.com/questions/tagged/javascript)[python](https://stackoverflow.com/questions/tagged/python)[c](https://stackoverflow.com/questions/tagged/c)[c\#](https://stackoverflow.com/questions/tagged/c)
Popular unanswered question
[Use Gradle Kotlin DSL in visual studio code](https://stackoverflow.com/questions/75870727)
[kotlin](https://stackoverflow.com/questions/tagged/kotlin)[visual-studio-code](https://stackoverflow.com/questions/tagged/visual-studio-code)[gradle](https://stackoverflow.com/questions/tagged/gradle)[gradle-kotlin-dsl](https://stackoverflow.com/questions/tagged/gradle-kotlin-dsl)
[](https://stackoverflow.com/users/11963435)
[isanghaessi](https://stackoverflow.com/users/11963435)
- 21
925 days ago
#### Linked
[1797](https://stackoverflow.com/questions/6760685/what-is-the-best-way-of-implementing-a-singleton-in-python?lq=1 "Question score (upvotes - downvotes)")
[What is the best way of implementing a singleton in Python?](https://stackoverflow.com/questions/6760685/what-is-the-best-way-of-implementing-a-singleton-in-python?noredirect=1&lq=1)
[1423](https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work-in-python?lq=1 "Question score (upvotes - downvotes)")
[How does the @property decorator work in Python?](https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work-in-python?noredirect=1&lq=1)
[77](https://stackoverflow.com/questions/6966772/using-the-call-method-of-a-metaclass-instead-of-new?lq=1 "Question score (upvotes - downvotes)")
[Using the \_\_call\_\_ method of a metaclass instead of \_\_new\_\_?](https://stackoverflow.com/questions/6966772/using-the-call-method-of-a-metaclass-instead-of-new?noredirect=1&lq=1)
[77](https://stackoverflow.com/questions/54254252/asyncio-vs-gevent?lq=1 "Question score (upvotes - downvotes)")
[Asyncio vs. Gevent](https://stackoverflow.com/questions/54254252/asyncio-vs-gevent?noredirect=1&lq=1)
[18](https://stackoverflow.com/questions/59341761/what-are-the-differences-between-a-classmethod-and-a-metaclass-method?lq=1 "Question score (upvotes - downvotes)")
[What are the differences between a \`classmethod\` and a metaclass method?](https://stackoverflow.com/questions/59341761/what-are-the-differences-between-a-classmethod-and-a-metaclass-method?noredirect=1&lq=1)
#### Related
[7512](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python?rq=3 "Question score (upvotes - downvotes)")
[What are metaclasses in Python?](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python?rq=3)
[18](https://stackoverflow.com/questions/476586/is-anyone-using-meta-meta-classes-meta-meta-meta-classes-in-python-other-lang?rq=3 "Question score (upvotes - downvotes)")
[Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages?](https://stackoverflow.com/questions/476586/is-anyone-using-meta-meta-classes-meta-meta-meta-classes-in-python-other-lang?rq=3)
[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)
[33](https://stackoverflow.com/questions/2005878/what-are-python-metaclasses-useful-for?rq=3 "Question score (upvotes - downvotes)")
[What are Python metaclasses useful for?](https://stackoverflow.com/questions/2005878/what-are-python-metaclasses-useful-for?rq=3)
[15](https://stackoverflow.com/questions/2907498/good-real-world-uses-of-metaclasses-e-g-in-python?rq=3 "Question score (upvotes - downvotes)")
[Good real-world uses of metaclasses (e.g. in Python)](https://stackoverflow.com/questions/2907498/good-real-world-uses-of-metaclasses-e-g-in-python?rq=3)
[88](https://stackoverflow.com/questions/5738470/whats-an-example-use-case-for-a-python-classmethod?rq=3 "Question score (upvotes - downvotes)")
[What's an example use case for a Python classmethod?](https://stackoverflow.com/questions/5738470/whats-an-example-use-case-for-a-python-classmethod?rq=3)
[5](https://stackoverflow.com/questions/6562538/metaclasses-in-python-a-couple-of-questions-to-clarify?rq=3 "Question score (upvotes - downvotes)")
[Metaclasses in Python: a couple of questions to clarify](https://stackoverflow.com/questions/6562538/metaclasses-in-python-a-couple-of-questions-to-clarify?rq=3)
[7](https://stackoverflow.com/questions/10361181/in-python-when-should-i-use-a-meta-class?rq=3 "Question score (upvotes - downvotes)")
[In Python, when should I use a meta class?](https://stackoverflow.com/questions/10361181/in-python-when-should-i-use-a-meta-class?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/71377962/what-is-the-purpose-of-metaclass-methods-being-defined-on-classes-but-not-instan?rq=3 "Question score (upvotes - downvotes)")
[What is the purpose of metaclass methods being defined on classes but not instances?](https://stackoverflow.com/questions/71377962/what-is-the-purpose-of-metaclass-methods-being-defined-on-classes-but-not-instan?rq=3)
#### [Hot Network Questions](https://stackexchange.com/questions?tab=hot)
- [Why definition of \\sett@b was changed in plain.tex?](https://tex.stackexchange.com/questions/752181/why-definition-of-settb-was-changed-in-plain-tex)
- [Why not use 上 in 跪在地下](https://chinese.stackexchange.com/questions/61617/why-not-use-%E4%B8%8A-in-%E8%B7%AA%E5%9C%A8%E5%9C%B0%E4%B8%8B)
- [Does excessive use of \[\[likely\]\] and \[\[unlikely\]\] really degrade program performance in C++?](https://stackoverflow.com/questions/79784809/does-excessive-use-of-likely-and-unlikely-really-degrade-program-perform)
- [Applying for TT at the beginning of a postdoc](https://academia.stackexchange.com/questions/221659/applying-for-tt-at-the-beginning-of-a-postdoc)
- [Picture and story ID looking for an image of an alien with a raspberry like face](https://scifi.stackexchange.com/questions/299525/picture-and-story-id-looking-for-an-image-of-an-alien-with-a-raspberry-like-face)
- [yet another machine giving O or X for sequences of positive numbers](https://puzzling.stackexchange.com/questions/133511/yet-another-machine-giving-o-or-x-for-sequences-of-positive-numbers)
- [Is it proper to describe my vocabulary as profound?](https://ell.stackexchange.com/questions/368684/is-it-proper-to-describe-my-vocabulary-as-profound)
- [Best formulation of Riemann hypothesis for a general audience](https://mathoverflow.net/questions/501311/best-formulation-of-riemann-hypothesis-for-a-general-audience)
- [Does car Wax paste contain any abrasive polishing components? as i am seeking a 100% pure wax for paint protection](https://mechanics.stackexchange.com/questions/99568/does-car-wax-paste-contain-any-abrasive-polishing-components-as-i-am-seeking-a)
- [Box around algorithm left vertical line alone](https://tex.stackexchange.com/questions/752192/box-around-algorithm-left-vertical-line-alone)
- [Why 1st law of thermodynamics is applied to cosmological expansion](https://physics.stackexchange.com/questions/860413/why-1st-law-of-thermodynamics-is-applied-to-cosmological-expansion)
- [Is it possible to create a language with no paradoxical statements?](https://philosophy.stackexchange.com/questions/131040/is-it-possible-to-create-a-language-with-no-paradoxical-statements)
- [two objects following two curves at the same time](https://blender.stackexchange.com/questions/339469/two-objects-following-two-curves-at-the-same-time)
- [How to make a specific program prefer Wi-Fi over Ethernet in Windows?](https://superuser.com/questions/1926203/how-to-make-a-specific-program-prefer-wi-fi-over-ethernet-in-windows)
- [How can I find common prefixes in file names to group them?](https://unix.stackexchange.com/questions/800287/how-can-i-find-common-prefixes-in-file-names-to-group-them)
- [Historical drama set in the Middle-Ages in Western Europe](https://movies.stackexchange.com/questions/128556/historical-drama-set-in-the-middle-ages-in-western-europe)
- [Adding a colormap to a solution curve of a vector field](https://tex.stackexchange.com/questions/752168/adding-a-colormap-to-a-solution-curve-of-a-vector-field)
- [Has there been any significant change to DOGE, or has it simply faded out of prominence?](https://politics.stackexchange.com/questions/93700/has-there-been-any-significant-change-to-doge-or-has-it-simply-faded-out-of-pro)
- [Is there a mechanism to end a baseball game that stays tied?](https://sports.stackexchange.com/questions/30158/is-there-a-mechanism-to-end-a-baseball-game-that-stays-tied)
- ["The standard deviation is the statistical measure that describes, on average, how far each data point is from the mean"?](https://stats.stackexchange.com/questions/670648/the-standard-deviation-is-the-statistical-measure-that-describes-on-average-h)
- [Importance of so in connecting the sentences](https://ell.stackexchange.com/questions/368721/importance-of-so-in-connecting-the-sentences)
- [What is a git command to remove all files from cloned repository but still be able to pull?](https://superuser.com/questions/1926254/what-is-a-git-command-to-remove-all-files-from-cloned-repository-but-still-be-ab)
- [Using LM1084 LDO without capacitors. Can that cause stability and heat dissipation design flaws in my 22V voltage limiter for a solar panel?](https://electronics.stackexchange.com/questions/756608/using-lm1084-ldo-without-capacitors-can-that-cause-stability-and-heat-dissipati)
- [Draw circumscribed sphere and inscribed sphere of regular tetrahedron](https://tex.stackexchange.com/questions/752135/draw-circumscribed-sphere-and-inscribed-sphere-of-regular-tetrahedron)
[Question feed](https://stackoverflow.com/feeds/question/392160 "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 [Code of Conduct](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
##### [Stack Overflow](https://stackoverflow.com/)
- [Questions](https://stackoverflow.com/questions)
- [Help](https://stackoverflow.com/help)
- [Chat](https://chat.stackoverflow.com/?tab=explore)
##### [Products](https://stackoverflow.co/)
- [Teams](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=teams)
- [Advertising](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=advertising)
- [Talent](https://stackoverflow.co/advertising/employer-branding/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=talent)
##### [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.10.6.34876 |
| Readable Markdown | null |
| Shard | 169 (laksa) |
| Root Hash | 714406497480128969 |
| Unparsed URL | com,stackoverflow!/questions/392160/what-are-some-concrete-use-cases-for-metaclasses s443 |