I'm looking for a way to make a list of string literals in a class.
class A:
def method(self):
print '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.