2

Given a class, how would I list all of its inner classes?

class Car:
    some_var = "var"

    class Engine:
        some_other_var = "var2"

    class Body:
        another_var = "var3"

Now given Car I want to be able to list or iterate over all of its inner classes (Engine, Body)

(Python 3.5)

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
bluesummers
  • 11,365
  • 8
  • 72
  • 108
  • Car.__dict__ should give you a starting point – Arjen Dijkstra Jun 03 '17 at 07:45
  • What version of Python are you using? – jpmc26 Jun 03 '17 at 07:45
  • 1
    Why do you want to define these classes inside `Car`? It's _possible_ to do that in Python, but rarely desirable. And you probably should be using instance attributes for those variables, not class attributes. You _can_ use class objects directly to store data like that, but the usual practice is to create instances of your classes. – PM 2Ring Jun 03 '17 at 07:50
  • 2
    `[c for c in vars(Car).values() if isinstance(c, type(Car))]` – metatoaster Jun 03 '17 at 07:51
  • @PM2Ring its a config file, it stores strings and I want the to have and ordered manner. – bluesummers Jun 03 '17 at 07:54
  • @jpmc26 python3.5 – bluesummers Jun 03 '17 at 07:54
  • You're using a .py file to store config data? There's probably a better way to do that... – PM 2Ring Jun 03 '17 at 08:12
  • @PM2Ring I was looking to user `configparser` but it does not support nesting, which is important to me. Do you have any other suggestions? – bluesummers Jun 03 '17 at 08:20
  • You could use JSON. See [here](https://gist.github.com/PM2Ring/8e819c4b6b1b27a3588567c9c0aa5f34) for a couple of options. Python's [`json`](https://docs.python.org/3/library/json.html#module-json) module makes it very easy to read & write JSON data. Another option is XML, but that's more tedious to process, and JSON is a lot easier for humans to read (and modify manually) than XML. – PM 2Ring Jun 03 '17 at 08:36
  • 1
    Also, for less verbosity than JSON (typing all the {, ", ","s ) you may take a look at YAML. But for sure, using nested classes just to store configuration is not a good approach. – jsbueno Jun 03 '17 at 09:25
  • 1
    for what reason using classes as config files are bad? – bluesummers Jun 03 '17 at 09:42

1 Answers1

5

You can do something like this:

import inspect
[d for d in dir(Car) if inspect.isclass(getattr(Car, d))]

It will give you a list of Class in your class Car.

Be mindful, variable d is a string

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304