Introspection

M

msj

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'
['A','BC']

Is this possible? Can anyone point me in the right direction?

Thanks.

/Martin
 
M

Miki

Hello Martin,
I'm looking for a way to make a list of string literals in a class.
from inspect import getsourcelines
from tokenize import generate_tokens, STRING, NUMBER

def is_literal(t):
return t[0] in (STRING, NUMBER)

def get_lieterals(obj):
lines, _ = getsourcelines(obj)
readline = iter(lines).next
return [t[1] for t in generate_tokens(readline) if is_literal(t)]

if __name__ == "__main__":
class A:
def f(self):
print "A", "B"

print get_lieterals(A)

HTH,
 
S

Steven D'Aprano

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'
['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()
 
J

Jason Scheirer

I'm looking for a way to make a list of string literals in a class.

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()

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top