473,657 Members | 2,661 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(getatt r(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 1585
Don't use built-ins as variable names. Your code will work if you
change this:
methodList = [str for str in names if callable(getatt r(obj, str))]
to this:
methodList = [s for s in names if callable(getatt r(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(getatt r(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(getatt r(obj, str))]

I'll bet it will work then.

-Larry
Mar 15 '07 #3
On Mar 15, 2:49 pm, "7stud" <bbxx789_0...@y ahoo.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(getatt r(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(getatt r(obj, str))]

instead, do something like this:

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

Have fun!

Mike

Mar 15 '07 #4

"7stud" <bb**********@y ahoo.comwrote in message
news:11******** **************@ n76g2000hsh.goo glegroups.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(getatt r(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(getatt r(obj, str))]

instead, do something like this:

methodList = [i for i in names if callable(getatt r(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(getatt r(obj, str))]

instead, do something like this:

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

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

genexps, unlike listcomps, make a new scope for their index variable.
Mar 16 '07 #9
Steve Holden <st***@holdenwe b.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

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

Similar topics

5
2719
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 last few bytes of uudecoded data are always mangled. Take a look of this hexdump output: Originals (decoded with Pan, each line is from a different file): 000c2c0 e1bf 00ff 2541 a9e4 a724 d9ff 0011a10 ff54 00d9 00093e0 fb4f a80d ffd9 c200 ffef...
19
7271
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. Specifically, I have a problem with this portion in the WHERE clause: DATEADD(Day,tblMyEventTableName.ReminderDays, @DateNow) Between CONVERT(smalldatetime,str(DATEPART(Month, @DateNow)+1) + '/' + str(DATEPART(Day, tblMyEventTableName.TaskDateTime)) + '/'...
20
551
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( ( d.getMonth()+1 ) < 10 ) { str = '0'; }
6
4059
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 given a set of characters (allowing repetitions of the same character) For example given the characters 'E' and 'H' and maximum length 3 the function should generate the sequences
1
1514
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 the answer is correct. When I hit the button the array variables seem to reinitialize to zero. Any ideas why this would happen? I have posted the vb behind code for the web page. Public Class WebForm1 Inherits System.Web.UI.Page
0
1751
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 output to the screen. The other program is main.cc, which wants to communicate with myProgram in real time using input/output redirection and two named pipes.
1
2587
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 cells - they are generated through the odswierz_frekfencje() function (listed below)-
2
3151
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 i change something in php file using in ajax function.it not refreshed,means its shows the previous result it not get updated.i can't understand whats the prob.this is the code i m using: <? include("config.inc.php"); //error_reporting(0); ...
18
1965
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 decrement it to the current quantity for example if tehre is a part woth part no 10023 and its quantity in show room is 20 and total quantity is 25 then if there is a sale of 2 parts then i have to add the sale and decrement the current quantity in the...
0
1655
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 XML source. Now to display data i hv use dataset to fetch data.so i m displaying data in datagrid/dataview. Now here comes a problem: Using Datagrid :
0
8319
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8837
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8739
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8612
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7347
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6175
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5638
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4171
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.