Python module class list

How can I get a list of all classes within current module in Python?

How can I get a list of all classes within current module in Python?

I’ve seen plenty of examples of people extracting all of the classes from a module, usually something like:

# foo.py class Foo: pass # test.py import inspect import foo for name, obj in inspect.getmembers(foo): if inspect.isclass(obj): print obj 

But I can’t find out how to get all of the classes from the current module.

# foo.py import inspect class Foo: pass def print_classes(): for name, obj in inspect.getmembers(. ): # what do I do here? if inspect.isclass(obj): print obj # test.py import foo foo.print_classes() 

This is probably something really obvious, but I haven’t been able to find anything. Can anyone help me out?

import sys current_module = sys.modules[__name__] 
import sys, inspect def print_classes(): for name, obj in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(obj): print(obj) 
clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass) 

Because inspect.getmembers() takes a predicate.

I don’t know if there’s a ‘proper’ way to do it, but your snippet is on the right track: just add import foo to foo.py, do inspect.getmembers(foo) , and it should work fine.

g = globals().copy() for name, obj in g.iteritems(): 

I was able to get all I needed from the dir built in plus getattr .

# Works on pretty much everything, but be mindful that # you get lists of strings back print dir(myproject) print dir(myproject.mymodule) print dir(myproject.mymodule.myfile) print dir(myproject.mymodule.myfile.myclass) # But, the string names can be resolved with getattr, (as seen below) 

Though, it does come out looking like a hairball:

def list_supported_platforms(): """ List supported platforms (to match sys.platform) @Retirms: list str: platform names """ return list(itertools.chain( *list( # Get the class's constant getattr( # Get the module's first class, which we wrote getattr( # Get the module getattr(platforms, item), dir( getattr(platforms, item) )[0] ), 'SYS_PLATFORMS' ) # For each include in platforms/__init__.py for item in dir(platforms) # Ignore magic, ourselves (index.py) and a base class. if not item.startswith('__') and item not in ['index', 'base'] ) )) 

How to list all functions in a module?, You can use dir(module) to see all available methods/attributes. Also check out PyDocs.

Читайте также:  Развертывание сервера nginx и php

Python Class 23

It can define functions, classes, and variables, and can also include runnable code. Any Python
Duration: 1:07:02

Python list classes in module

"""Returns a list of (name, value) for each class""" import sys import inspect clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)

How to import a class from another file in Python ?, Python modules can get access to code from another module by importing the file/function using import. The import statement is that the

Import a list of classes from a module

Looking to import a list of classes and then use them later in the script. Therefore, the from x import * logic does not work. Here is a more specific layout of what I am looking to do.

class_list = [x, y, z, zz, zzz] from my_module import class_list 

and then later on in the code still be able to call x.random_attribute . Not sure if this is possible!

To clarify I am trying to avoid the following:

from my_module import x, y, z, zz, zzz 

as I have about 50 class objects I am importing and more will be added over time. Would love to have the list as a separate object.

class_list = ['x', 'y', 'z', 'zz', 'zzz'] for c in class_list: exec('from my_module import ' + c) 

How do I get all the classes in a module? [duplicate], Try this: import importlib, inspect inspect.getmembers( importlib.import_module(«your_module»), inspect.isclass ).

How do I get all the classes in a module? [duplicate]

How do I get all the classes in a module? For example if a module has classes A, B and C, how do I get the names of all these classes through code?

import importlib, inspect inspect.getmembers( importlib.import_module("your_module"), inspect.isclass ) 

this will give you what you are looking for.

How to Get a List of Class Attributes in Python?, Method 1: To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir() .

Источник

List classes, methods and functions in a module (Python recipe) by Anand

The recipe provides a method «describe» which takes a module as argument and describes classes, methods and functions in the module. The method/function description provides information on the function/method arguments using the inspect module.

Copy to clipboard

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
#!/usr/bin/env python # Describe classes, methods and functions in a module. # Works with user-defined modules, all Python library # modules, including built-in modules. import inspect import os, sys INDENT=0 def wi(*args): """ Function to print lines indented according to level """ if INDENT: print ' '*INDENT, for arg in args: print arg, print def indent(): """ Increase indentation """ global INDENT INDENT += 4 def dedent(): """ Decrease indentation """ global INDENT INDENT -= 4 def describe_builtin(obj): """ Describe a builtin function """ wi('+Built-in Function: %s' % obj.__name__) # Built-in functions cannot be inspected by # inspect.getargspec. We have to try and parse # the __doc__ attribute of the function. docstr = obj.__doc__ args = '' if docstr: items = docstr.split('\n') if items: func_descr = items[0] s = func_descr.replace(obj.__name__,'') idx1 = s.find('(') idx2 = s.find(')',idx1) if idx1 != -1 and idx2 != -1 and (idx2>idx1+1): args = s[idx1+1:idx2] wi('\t-Method Arguments:', args) if args=='': wi('\t-Method Arguments: None') print def describe_func(obj, method=False): """ Describe the function object passed as argument. If this is a method object, the second argument will be passed as True """ if method: wi('+Method: %s' % obj.__name__) else: wi('+Function: %s' % obj.__name__) try: arginfo = inspect.getargspec(obj) except TypeError: print return args = arginfo[0] argsvar = arginfo[1] if args: if args[0] == 'self': wi('\t%s is an instance method' % obj.__name__) args.pop(0) wi('\t-Method Arguments:', args) if arginfo[3]: dl = len(arginfo[3]) al = len(args) defargs = args[al-dl:al] wi('\t--Default arguments:',zip(defargs, arginfo[3])) if arginfo[1]: wi('\t-Positional Args Param: %s' % arginfo[1]) if arginfo[2]: wi('\t-Keyword Args Param: %s' % arginfo[2]) print def describe_klass(obj): """ Describe the class object passed as argument, including its methods """ wi('+Class: %s' % obj.__name__) indent() count = 0 for name in obj.__dict__: item = getattr(obj, name) if inspect.ismethod(item): count += 1;describe_func(item, True) if count==0: wi('(No members)') dedent() print def describe(module): """ Describe the module object passed as argument including its classes and functions """ wi('[Module: %s]\n' % module.__name__) indent() count = 0 for name in dir(module): obj = getattr(module, name) if inspect.isclass(obj): count += 1; describe_klass(obj) elif (inspect.ismethod(obj) or inspect.isfunction(obj)): count +=1 ; describe_func(obj) elif inspect.isbuiltin(obj): count += 1; describe_builtin(obj) if count==0: wi('(No members)') dedent() if __name__ == "__main__": import sys if len(sys.argv)2: sys.exit('Usage: %s ' % sys.argv[0]) module = sys.argv[1].replace('.py','') mod = __import__(module) describe(mod) 

This came as a question in our local Python mailing list (BangPypers). I wrote up the above solution to provide a quick summary of a module in terms of classes, and simple method descriptions. The ‘inspect’ module makes this task relatively easy.

[Edit] — Added support for built-in functions/methods. [Edit 22/10/08] — Changes in printing style.

Источник

How do I get a list of all instances of a given class in Python?

Display the count of instances of a class using the gc module

Example

In this example, we will calculate and display the count of instances −

import gc # Create a Class class Demo(object): pass # Creating 4 objects ob1 = Demo() ob2 = Demo() ob3 = Demo() ob4 = Demo() # Calculating and displaying the count of instances res = sum(1 for k in gc.get_referrers(Demo) if k.__class__ is Demo) print("Count the instances token punctuation">,res)

Output

Display the instances of a class using weakref module

The weakref module can also be used to get the instances of a class. First, we will install the weakref module using pip −

To use the gc module, use the import −

Example

Let us now see an example −

import weakref # Create a Demo() function class Demo: instanceArr = [] def __init__(self, name=None): self.__class__.instanceArr.append(weakref.proxy(self)) self.name = name # Create 3 objects ob1 = Demo('ob1') ob2 = Demo('ob2') ob3 = Demo('ob3') # Display the Instances for i in Demo.instanceArr: print(i.name)

Источник

Оцените статью