473,394 Members | 2,090 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

problem with str()

I can't get the str() method to work in the following code(the last
line produces an error):

============
class test:
"""class test"""
def __init__(self):
"""I am init func!"""
self.num = 10
self.num2 = 20
def someFunc(self):
"""I am someFunc in test!"""
print "hello"
obj = test()
obj.someFunc()
names = dir(obj)
print names

methodList = [str for str in names if callable(getattr(obj, str))]
print methodList

x = getattr(obj, methodList[0]).__doc__
print x
print type(x)
print str(getattr(obj, methodList[0]).__doc__)
===========

Here is the output:

$ python test1.py
hello
['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc']
['__init__', 'someFunc']
I am init func!
<type 'str'>
Traceback (most recent call last):
File "test1.py", line 23, in ?
print str(getattr(obj, methodList[0]).__doc__)
TypeError: 'str' object is not callable

This is part of some code in Diving Into Python,Chapter 4. In case a
function doesn't have a __doc__ string, and therefore __doc__ returns
None, the code needs to convert each __doc__ to a string so that the
result is guaranteed to be a string.

Mar 15 '07 #1
13 1573
Don't use built-ins as variable names. Your code will work if you
change this:
methodList = [str for str in names if callable(getattr(obj, str))]
to this:
methodList = [s for s in names if callable(getattr(obj, s))]
Mar 15 '07 #2
7stud wrote:
I can't get the str() method to work in the following code(the last
line produces an error):

============
class test:
"""class test"""
def __init__(self):
"""I am init func!"""
self.num = 10
self.num2 = 20
def someFunc(self):
"""I am someFunc in test!"""
print "hello"
obj = test()
obj.someFunc()
names = dir(obj)
print names

methodList = [str for str in names if callable(getattr(obj, str))]
print methodList

x = getattr(obj, methodList[0]).__doc__
print x
print type(x)
print str(getattr(obj, methodList[0]).__doc__)
===========

Here is the output:

$ python test1.py
hello
['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc']
['__init__', 'someFunc']
I am init func!
<type 'str'>
Traceback (most recent call last):
File "test1.py", line 23, in ?
print str(getattr(obj, methodList[0]).__doc__)
TypeError: 'str' object is not callable

This is part of some code in Diving Into Python,Chapter 4. In case a
function doesn't have a __doc__ string, and therefore __doc__ returns
None, the code needs to convert each __doc__ to a string so that the
result is guaranteed to be a string.
You masked the built-in str method in your list comprehension.

Try changing to:

methodList = [s for s in names if callable(getattr(obj, str))]

I'll bet it will work then.

-Larry
Mar 15 '07 #3
On Mar 15, 2:49 pm, "7stud" <bbxx789_0...@yahoo.comwrote:
I can't get the str() method to work in the following code(the last
line produces an error):

============
class test:
"""class test"""
def __init__(self):
"""I am init func!"""
self.num = 10
self.num2 = 20
def someFunc(self):
"""I am someFunc in test!"""
print "hello"

obj = test()
obj.someFunc()
names = dir(obj)
print names

methodList = [str for str in names if callable(getattr(obj, str))]
print methodList

x = getattr(obj, methodList[0]).__doc__
print x
print type(x)
print str(getattr(obj, methodList[0]).__doc__)
===========

Here is the output:

$ python test1.py
hello
['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc']
['__init__', 'someFunc']
I am init func!
<type 'str'>
Traceback (most recent call last):
File "test1.py", line 23, in ?
print str(getattr(obj, methodList[0]).__doc__)
TypeError: 'str' object is not callable

This is part of some code in Diving Into Python,Chapter 4. In case a
function doesn't have a __doc__ string, and therefore __doc__ returns
None, the code needs to convert each __doc__ to a string so that the
result is guaranteed to be a string.
Your string comprehension over wrote the str built-in method, turning
it into a variable. If you just type "str" (without the quotes) into
the interpreter, it'll spit out 'someFunc'. Thus, you cannot use str
as the iterator in your code:

methodList = [str for str in names if callable(getattr(obj, str))]

instead, do something like this:

methodList = [i for i in names if callable(getattr(obj, i))]

Have fun!

Mike

Mar 15 '07 #4

"7stud" <bb**********@yahoo.comwrote in message
news:11**********************@n76g2000hsh.googlegr oups.com...
|I can't get the str() method to work in the following code(the last
| line produces an error):

If you 'print str' here

| methodList = [str for str in names if callable(getattr(obj, str))]

and again here, you will see the problem; you have reassigned the name
'str' to something else by using it in the list comp. Hence the advice to
never reuse
builtin names unless you mean to lose access to the builtin object.

|print str(getattr(obj, methodList[0]).__doc__)

Here I presume you want the builtin function. Too bad... ;-)

Terry Jan Reedy

Mar 15 '07 #5
Sheesh! You would think that after looking at every inch of the code
for way too many hours, at some point that would have poked me in the
eye.

Thanks all.

Mar 15 '07 #6
7stud wrote:
Sheesh! You would think that after looking at every inch of the code
for way too many hours, at some point that would have poked me in the
eye.

Thanks all.
Get yourself a stuffed bear, and next time you have this kind of problem
spend a few minutes explaining to the bear exactly how your program
can't possibly be wrong. Works like a charm.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

Mar 16 '07 #7
En Thu, 15 Mar 2007 17:32:24 -0300, <ky******@gmail.comescribió:
methodList = [str for str in names if callable(getattr(obj, str))]

instead, do something like this:

methodList = [i for i in names if callable(getattr(obj, i))]
The fact that a list comprehension "leaks" its variables into the
containing scope is a bit weird.
A generator expression doesn't:

pystr
<type 'str'>
pyw = (str for str in range(10))
pyw
<generator object at 0x00AD7C38>
pystr
<type 'str'>
pyw.next()
0
pystr
<type 'str'>

--
Gabriel Genellina

Mar 16 '07 #8
ky******@gmail.com writes:
methodList = [str for str in names if callable(getattr(obj, str))]

instead, do something like this:

methodList = [i for i in names if callable(getattr(obj, i))]
or:

methodList = list(str for str in names if callable(getattr(obj, str)))

genexps, unlike listcomps, make a new scope for their index variable.
Mar 16 '07 #9
Steve Holden <st***@holdenweb.comwrote:
7stud wrote:
Sheesh! You would think that after looking at every inch of the code
for way too many hours, at some point that would have poked me in the
eye.

Thanks all.
Get yourself a stuffed bear, and next time you have this kind of problem
spend a few minutes explaining to the bear exactly how your program
can't possibly be wrong. Works like a charm.
A rubber ducky works much better for that, btw -- more easily washable
than a stuffed bear, for example.
Alex
Mar 16 '07 #10
Alex Martelli wrote:
Steve Holden <st***@holdenweb.comwrote:
>7stud wrote:
>>Sheesh! You would think that after looking at every inch of the code
for way too many hours, at some point that would have poked me in the
eye.

Thanks all.
Get yourself a stuffed bear, and next time you have this kind of problem
spend a few minutes explaining to the bear exactly how your program
can't possibly be wrong. Works like a charm.

A rubber ducky works much better for that, btw -- more easily washable
than a stuffed bear, for example.
But stuffed bears are so much more knowledgeable about the minutiae of
software design.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

Mar 16 '07 #11
On Mar 15, 5:31 pm, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
The fact that a list comprehension "leaks" its variables into the
containing scope is a bit weird.
A generator expression doesn't:

pystr
<type 'str'>
pyw = (str for str in range(10))
pyw
<generator object at 0x00AD7C38>
pystr
<type 'str'>
pyw.next()
0
pystr
<type 'str'>
On Mar 15, 5:34 pm, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
or:

methodList = list(str for str in names if callable(getattr(obj, str)))

genexps, unlike listcomps, make a new scope for their index variable.

Thanks.

Mar 16 '07 #12
Steve Holden <st***@holdenweb.comwrote:
...
Get yourself a stuffed bear, and next time you have this kind of problem
spend a few minutes explaining to the bear exactly how your program
can't possibly be wrong. Works like a charm.
A rubber ducky works much better for that, btw -- more easily washable
than a stuffed bear, for example.
But stuffed bears are so much more knowledgeable about the minutiae of
software design.
And yet, the key to Python's strength is duck typing -- if you can teach
the duck to type, you've got it made.
Alex
Mar 16 '07 #13
Alex Martelli wrote:
Steve Holden <st***@holdenweb.comwrote:
...
>>>Get yourself a stuffed bear, and next time you have this kind of problem
spend a few minutes explaining to the bear exactly how your program
can't possibly be wrong. Works like a charm.
A rubber ducky works much better for that, btw -- more easily washable
than a stuffed bear, for example.
But stuffed bears are so much more knowledgeable about the minutiae of
software design.

And yet, the key to Python's strength is duck typing -- if you can teach
the duck to type, you've got it made.

That's bearly a joke at all :)

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

Mar 16 '07 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Juho Saarikko | last post by:
I made a Python script which takes Usenet message bodies from a database, decodes uuencoded contents and inserts them as Large Object into a PostGreSQL database. However, it appears that the to...
19
by: Lauren Quantrell | last post by:
I have a stored procedure using Convert where the exact same Convert string works in the SELECT portion of the procedure but fails in the WHERE portion. The entire SP is listed below....
20
by: rhino | last post by:
This worked before October now it does not work. I think I know where the trouble is but I don't know how to fix it. function findVerse() { var d = new Date(); var str; if( (...
6
by: chiara | last post by:
Hi everybody! I am just at the beginning as a programmer, so maybe this is a stupid question...Anyway,I need to write a function in C to generate generate all possible strings of given length...
1
by: GL | last post by:
I am trying to develop a prgram that randomly selects numbers for an addition program, then when the check answer button is pressed it colors the answer text field either green or red depending if...
0
by: abottchow | last post by:
Hi all, I'm new to the group and am seeking your advice on my Linux programming problem. Two programs are involved. One is myProgram.cc, which reads user's input from keyboard and prints...
1
by: sp | last post by:
Hello I have a problem with the refresh performance in datagrid – when datagrid is being shown it is so slow that I can see one by one cells is drawn -datagrid contains about 35x40 of...
2
by: shivendravikramsingh | last post by:
hi friends, i m using a ajax function for retrieving some values from a database table,and display the values in required field,my prob is that the ajax function i m using is working f9 once,but if...
18
omerbutt
by: omerbutt | last post by:
AJAX PROB WITH MULTIPLE RECORDS helo iam having problem in ma code will any body look out an help, i am trying t add sale record in the database and the checkthe quantity of the part slod and...
0
by: webaccess | last post by:
Hi Friends ..!! I want to use datagrid/dataview control to data in tablular format,also I want to add paging and format the data of table column. Problem is data is coming from API Dom in as...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.