2

If I have a file, say first.py, which looks like this -

class Person(object): pass class Dog(object): pass 

and I have a second file, second.py. How can I get all the classes that were defined in first.py in second.py?

Perhaps I should mention that the use-case I'm trying to implement is similar to the one that happens when initializing models in Django - When I run the manage.py sql myapp command, I assume Django goes through all my models in models.py and generates an SQL query for them.

So what I'm trying to do is similar to what Django does when it takes all models defined in models.py.

How can I get all the user defined classes from a file? (Unless there's a smarter way to do what Django does)

Thanks in advance!

1
  • Seems like an easy answer to this would be to write the user-defined classes in such a way that they conform to a particular pattern, i.e., class PersonCustom, DogCustom, etc., or give each one an attribute that defines it as something that will be dynamically collected later on. Commented Jun 14, 2015 at 20:50

2 Answers 2

3

If you have a file first.py, in second.py, you would have to write the following code to return all the user-defined classes in first.py:

import first from types import * userDefinedClasses = [i for i in dir(first) if type(getattr(first, i)) is TypeType] 

In your simple example, pre-defining first.py, dir(first) would return the list ['Dog', 'Person', '__builtins__', '__doc__', '__file__', '__name__', '__package__']. To prune it, you would have to use the above compressed for loop to check the type of each object in the directory of first.

This would return all objects in first with type "type", which is practically all user-defined classes.

Sign up to request clarification or add additional context in comments.

1 Comment

The problem with this solution is that it'll also return things that weren't explicitly defined in first.py. I.E if I've imported another module in first.py, then it'll also show up in your code, despite not being explicitly written in first.py
0

All django-Models are subclasses of models.Model which has a meta class, that collects all model-subclasses. In general it is not possible to get all 'user-defined' classes.

2 Comments

The first half of this answer is true, but the second is not.
@Daniel could you please elaborate on the meta class collecting all model subclasses? How is that done?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.