Determine if a Python class is an Abstract Base Class or Concrete

2024/11/20 1:51:03

My Python application contains many abstract classes and implementations. For example:

import abc
import datetimeclass MessageDisplay(object):__metaclass__ = abc.ABCMeta@abc.abstractpropertydef display(self, message):passclass FriendlyMessageDisplay(MessageDisplay):def greet(self):hour = datetime.datetime.now().timetuple().tm_hourif hour < 7:raise Exception("Cannot greet while asleep.")elif hour < 12:self.display("Good morning!")elif hour < 18:self.display("Good afternoon!")elif hour < 20:self.display("Good evening!")else:self.display("Good night.")class FriendlyMessagePrinter(FriendlyMessageDisplay):def display(self, message):print(message)

FriendlyMessagePrinter is a concrete class that we can use...

FriendlyMessagePrinter().greet()
Good night.

...but MessageDisplay and FriendlyMessageDisplay are abstract classes and attempting to instantiate one would result in an error:

TypeError: Can't instantiate abstract class MessageDisplay with abstract methods say

How can I check if a given class object is an (uninstantiatable) abstract class?

Answer
import inspect
print(inspect.isabstract(object))                  # False
print(inspect.isabstract(MessageDisplay))          # True
print(inspect.isabstract(FriendlyMessageDisplay))  # True
print(inspect.isabstract(FriendlyMessagePrinter))  # False

This checks that the internal flag TPFLAGS_IS_ABSTRACT is set in the class object, so it can't be fooled as easily as your implementation:

class Fake:__abstractmethods__ = 'bluh'print(is_abstract(Fake), inspect.isabstract(Fake)) # True, False
https://en.xdnf.cn/q/26374.html

Related Q&A

Pandas printing ALL dtypes

This seems like a very simple problem, however its driving me round the bend. Im sure it should be solved by RTFM, but Ive looked at the options and I can see the one to fix it.I just want to print the…

Which Python API should be used with Mongo DB and Django

I have been going back and forth over which Python API to use when interacting with Mongo. I did a quick survey of the landscape and identified three leading candidates.PyMongo MongoEngine MingIf you w…

Save a list to a .txt file

Is there a function in python that allows us to save a list in a txt file and keep its format?If I have the list:values = [1,2,3]can I save it to a file that contains:[1,2,3]So far I print parts of th…

How to run a python script like pm2 for nodejs

Ive used pm2 for my Node.js script and I love it. Now I have a python script which collect streaming data on EC2. Sometimes the script bombs out and I would like a process manager to restart itself lik…

Resize rectangular image to square, keeping ratio and fill background with black

Im trying to resize a batch of grayscale images that are 256 x N pixels (N varies, but is always ≤256). My intention is to downscale the images.The resize would have to output a square (1:1) image, wi…

How to capture arbitrary paths at one route in FastAPI?

Im serving React app from FastAPI by mounting app.mount("/static", StaticFiles(directory="static"), name="static")@app.route(/session) async def renderReactApp(request: Re…

Changing the active class of a link with the twitter bootstrap css in python/flask

I got the following html snippet from my page template.html.<ul class=nav><li class="active"><a href=/>Home</a></li><li><a href=/lorem>Lorem</a>…

overwriting a spark output using pyspark

I am trying to overwrite a Spark dataframe using the following option in PySpark but I am not successfulspark_df.write.format(com.databricks.spark.csv).option("header", "true",mode=…

How to patch a constant in python

I have two different modules in my project. One is a config file which containsLOGGING_ACTIVATED = FalseThis constant is used in the second module (lets call it main) like the following:if LOGGING_ACTI…

Python script for minifying CSS? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…