How can I dynamically get the set of classes from the current python module?
I have a python module that defines a number of classes:
class A(object):
def __call__(self):
print "ran a"
class B(object):
def __call__(self):
print "ran b"
class C(object):
def __call__(self):
print "ran c"
From within the module, how might I add an attribute that gives me all of the classes?
dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from within the module.
From outside of the module, I can simply use getattr(mod, 'A')
, but I don't have a self
kind of module from within the module itself.
This seems pretty obvious. Can someone tell me what I'm missing?
Asked by: Chester918 | Posted: 28-01-2022
Answer 1
import sys
getattr(sys.modules[__name__], 'A')
Answered by: Chester462 | Posted: 01-03-2022
Answer 2
You can smash this into one for statement, but that'd have messy code duplication.
import sys
import types
this_module = sys.modules[__name__]
[x for x in
[getattr(this_module, x) for x in dir(this_module)]
if type(x) == types.ClassType]
Answered by: Clark863 | Posted: 01-03-2022
Answer 3
classes = [x for x in globals().values() if isinstance(x, type)]Answered by: Marcus344 | Posted: 01-03-2022
Similar questions
reflection - How to dynamically load a Python class
Given a string of a Python class, e.g. my_package.my_module.MyClass, what is the best possible way to load it?
In other words I am looking for a equivalent Class.forName() in Java, function in Python. It needs to work on Google App Engine.
Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:
my_clas...
reflection - Dynamically decompose list into variables in Python
I have 2 dimensional list created at runtime (the number of entries in either dimension is unknown). For example:
long_list = [ [2, 3, 6], [3, 7, 9] ]
I want to iterate through it by getting the ith entry from each list inside the long_list:
for entry in long_list.iter():
#entry will be [2, 3] then [3, 7] then [6, 9]
I know that Python's itertools.izip...
reflection - Is it possible to dynamically populate Python methods with code?
I have a number of methods that are of the following format:
def p_methodone(a):
pass
def p_methodtwo(a):
pass
...
I would like to remove the pass and populate these methods with the code a[0] = a[1]. Is it possible to do this in Python dynamically using something like reflection? The reason being is that I have a lot of these methods, and the c...
reflection - access object members from dynamically added methods in python
I have problem sharing members of a class with its dynamically generated methods.
For example below x accessed from __init__ and from normal_test is different fro x accessed from dynamically bounded methods test and setx:
class Foo:
def __init__(self):
self.x = 10
def normal_test(self):
print self.x...
reflection - Python dynamically add property always returns same result
I'm relatively new to python. I created this minimal sample to demonstrate my problem. Within a loop I add some properties to my class during runtime. If I query the properties later I always get the same result. I printed and checked the function instance variables of the function and the property and they all differ as expected. When I invoke the properties I always end up in the result of the last property.
python - Serving dynamically generated ZIP archives in Django
How to serve users a dynamically generated ZIP archive in Django?
I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.
python - Dynamically update ModelForm's Meta class
I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from as_p(), as_ul(), etc does not reflect the updated Meta exclude.
I assume then that the html is generated when the ModelForm is created not when the as_*() is called. Is there a way to force the update of the HTML...
reflection - How to dynamically load a Python class
Given a string of a Python class, e.g. my_package.my_module.MyClass, what is the best possible way to load it?
In other words I am looking for a equivalent Class.forName() in Java, function in Python. It needs to work on Google App Engine.
Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:
my_clas...
python - How do I retrieve a Django model class dynamically?
Without having the full module path of a Django model, is it possible to do something like:
model = 'User' [in Django namespace]
model.objects.all()
...as opposed to:
User.objects.all().
EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g.,
model = django.authx.models.User
python - Jython, Query multiple columns dynamically
I am working with a oracle database and Jython.
I can get data pulled from the database no problem.
results = statement.executeQuery("select %s from %s where column_id = '%s'", % (column, table, id))
This works fine if I want to pull one column of data.
Say I wanted to loop threw a list like this:
columns = ['column1', 'column2', 'column3', 'column4', 'colum...
python - Django: How to create a model dynamically just for testing
I have a Django app that requires a settings attribute in the form of:
RELATED_MODELS = ('appname1.modelname1.attribute1',
'appname1.modelname2.attribute2',
'appname2.modelname3.attribute3', ...)
Then hooks their post_save signal to update some other fixed model depending on the attributeN defined.
I would like to test ...
python - Doctest for dynamically created objects
What is the best way to test code like this (the one below obviously fails while object is created in different block every time):
def get_session(db_name, verbose, test):
"""Returns current DB session from SQLAlchemy pool.
>>> get_session('Mmusc20090126', False, True)
<sqlalchemy.orm.session.Session object at 0xfb5ff0>
"""
if test:
engine = create_engine('sqlite:///:memory:', echo=verb...
python - Dynamically specifying tags while using replaceWith in Beautiful Soup
Previously I asked this question and got back this BeautifulSoup example code, which after some consultation locally, I decided to go with.
>>> from BeautifulSoup import BeautifulStoneSoup
>>> html = """
... <config>
... <links>
... <link name="Link1" id...
python - How to make these dynamically typed functions type-safe?
Closed. This question needs to be more focused. It ...
python - How do i output a dynamically generated web page to a .html page instead of .py cgi page?
So ive just started learning python on WAMP, ive got the results of a html form using cgi, and successfully performed a database search with mysqldb. I can return the results to a page that ends with .py by using print statements in the python cgi code, but i want to create a webpage that's .html and have that returned to the user, and/or keep them on the same webaddress when the database search results return.
th...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python