Introspection

Jason Scheirer jason.scheirer at gmail.com
Wed Jan 6 16:17:49 EST 2010


On Jan 6, 8:38 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Wed, 06 Jan 2010 06:53:40 -0800, m... at infoserv.dk wrote:
> > I'm looking for a way to make a list of string literals in a class.
>
> > Example:
>
> > class A:
> >    def method(self):
> >        print 'A','BC'
>
> >>>> ExtractLiterals(A)
> > ['A','BC']
>
> > Is this possible? Can anyone point me in the right direction?
>
> class A:
>     def extract_literals(self):
>         return "A BC".split()
>     def method(self):
>         print self.extract_literals()
>
> a = A()
> a.extract_literals()
>
> --
> Steven

Slightly more robust than Miki's solution insofar as it doesn't
require the source to exist in a .py file:

import types
def extract_literals(klass):
    for attr in (getattr(klass, item) for item in dir(klass)):
        if isinstance(attr, types.MethodType):
            for literal in attr.im_func.func_code.co_consts:
                if isinstance(literal, basestring):
                    yield literal

class full_of_strings(object):
    def a(self):
        return "a", "b", "c"
    def b(self):
        "y", "z"

print list(extract_literals(full_of_strings))
['a', 'b', 'c', 'y', 'z']

print list(extract_literals(full_of_strings()))
['a', 'b', 'c', 'y', 'z']

Note that this is evil and should be avoided.



More information about the Python-list mailing list