473,786 Members | 2,578 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to convert string to list or tuple

a = "(1,2,3)"
I want convert a to tuple:(1,2,3),b ut tuple(a) return ('(', '1', ',',
'2', ',', '3', ')') not (1,2,3)
Jul 19 '05
16 23017
Steven Bethard wrote:
Duncan Booth wrote:
any new style class you have defined and call any of its methods with
whatever arguments I wish.


Any new style class that I've defined? Or just any one I pass in as
part of dict(__builtins __=None, ...)? If the former, could you
elaborate? If the latter, then yes, I can see the problem. However
for the case where all you pass in is dict(__builtins __=None), is
there still a risk? Note that in the OP's case, all that is necessary
is constant parsing, so no names need to be available.

Any new style class you have defined is accessible through
object.__subcla sses__(), and as I showed object itself is always accessible
through {}.__class__.__ bases__[0].

I'm assuming that the source code for your program is available. That means
I can find the name of an interesting class which has a method that does
something destructive, and call it.

e.g. Assuming that the MyDatabase class does something nasty to a file:
class MyDatabase(obje ct): def __init__(self, filename):
self.filename = filename
def initialise(self ):
print "Splat %s" % self.filename

eval('''[ cls for cls in {}.__class__.__ bases__[0].__subclasses__ ()

if 'MyDatabase' in `cls`
][0]('importantfile ').initialise() ''', dict(__builtins __=None))
Splat importantfile
Jul 19 '05 #11
Duncan Booth wrote:
e.g. Assuming that the MyDatabase class does something nasty to a file:
class MyDatabase(obje ct):
def __init__(self, filename):
self.filename = filename
def initialise(self ):
print "Splat %s" % self.filename
eval('''[ cls for cls in {}.__class__.__ bases__[0].__subclasses__ ()


if 'MyDatabase' in `cls`
][0]('importantfile ').initialise() ''', dict(__builtins __=None))
Splat importantfile


Interestingly, I don't seem to be able to create a file object as a
class attribute in restricted mode:

py> class C(object):
.... def __init__(self):
.... self.f = file('temp.txt' , 'w')
....
py> eval('''[ cls for cls in {}.__class__.__ bases__[0].__subclasses__ ()
if cls.__name__ == 'C'][0]().f.write("stu ff")''', dict(__builtins __=None))
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<string>", line 0, in ?
AttributeError: 'C' object has no attribute 'f'
py> eval('''[ cls for cls in {}.__class__.__ bases__[0].__subclasses__ ()
if cls.__name__ == 'C'][0]().__dict__''', dict(__builtins __=None))
{}

I don't get an error for calling the file constructor, but the f
attribute is never set AFAICT.

STeVe
Jul 19 '05 #12
Steven Bethard wrote:
Interestingly, I don't seem to be able to create a file object as a
class attribute in restricted mode:

py> class C(object):
... def __init__(self):
... self.f = file('temp.txt' , 'w')
...
py> eval('''[ cls for cls in
{}.__class__.__ bases__[0].__subclasses__ () if cls.__name__ ==
'C'][0]().f.write("stu ff")''', dict(__builtins __=None)) Traceback
(most recent call last):
File "<interacti ve input>", line 1, in ?
File "<string>", line 0, in ?
AttributeError: 'C' object has no attribute 'f'
py> eval('''[ cls for cls in
{}.__class__.__ bases__[0].__subclasses__ () if cls.__name__ ==
'C'][0]().__dict__''', dict(__builtins __=None)) {}


Weird. I copied and paste your class and eval exactly (apart from deleting
the ... prompts) and it worked exactly as expected: writing 'stuff' to
temp.txt. (Python 2.4)

Jul 19 '05 #13
flyaflya wrote:
a = "(1,2,3)"
I want convert a to tuple:(1,2,3),b ut tuple(a) return ('(', '1', ',',
'2', ',', '3', ')') not (1,2,3)


Probably a bit late... but there's always listquote - It's part of the
pythonutils module.

http://www.voidspace.org.uk/python/pythonutils.html

It will turn strings to lists, including nested lists.

Best Regards,

Fuzzy
http://www.voidspace.org.uk/python

Jul 19 '05 #14
Duncan Booth wrote:
Steven Bethard wrote:

Interestingly , I don't seem to be able to create a file object as a
class attribute in restricted mode:

py> class C(object):
... def __init__(self):
... self.f = file('temp.txt' , 'w')
...
py> eval('''[ cls for cls in
{}.__class__. __bases__[0].__subclasses__ () if cls.__name__ ==
'C'][0]().f.write("stu ff")''', dict(__builtins __=None)) Traceback
(most recent call last):
File "<interacti ve input>", line 1, in ?
File "<string>", line 0, in ?
AttributeErro r: 'C' object has no attribute 'f'
py> eval('''[ cls for cls in
{}.__class__. __bases__[0].__subclasses__ () if cls.__name__ ==
'C'][0]().__dict__''', dict(__builtins __=None)) {}


Weird. I copied and paste your class and eval exactly (apart from deleting
the ... prompts) and it worked exactly as expected: writing 'stuff' to
temp.txt. (Python 2.4)


So, I played around with this a little bit. If I start up a new
interpreter and type it in like above, I get the behavior you do. What
I had actually done (abbreviated) was:

py> class C(object):
.... pass
....
py> class C(object):
.... def __init__(self):
.... self.f = file('temp.txt' , 'w')
....
py> eval('''[ cls for cls in {}.__class__.__ bases__[0].__subclasses__ ()
if cls.__name__ == 'C'][0]().f.write("stu ff")''', dict(__builtins __=None))
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<string>", line 0, in ?
AttributeError: 'C' object has no attribute 'f'

And the problem with this is that both __main__.C objects are now
subclasses of object:

py> eval('''[ cls for cls in {}.__class__.__ bases__[0].__subclasses__ ()
if cls.__name__ == 'C']''', dict(__builtins __=None))
[<class '__main__.C'>, <class '__main__.C'>]

So I was getting the wrong __main__.C object. Sorry for the confusion!

Now, even using this technique, *your* code can't call the file constructor:

py> class C(object):
.... def __init__(self):
.... self.file = file
....
py> eval('''[ cls for cls in {}.__class__.__ bases__[0].__subclasses__ ()
if cls.__name__ == 'C'][-1]().file("temp.t xt", "w")''',
dict(__builtins __=None))
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<string>", line 0, in ?
IOError: file() constructor not accessible in restricted mode

But unless the person eval-ing your code *only* writes immaculate code I
can see that you can probably screw them. ;) I wonder why
__subclasses__ isn't a restricted attribute... Is it ever used for
something that isn't evil? ;)

STeVe
Jul 19 '05 #15
Steven Bethard schreef:
But unless the person eval-ing your code *only* writes immaculate code I
can see that you can probably screw them. ;) I wonder why
__subclasses__ isn't a restricted attribute... Is it ever used for
something that isn't evil? ;)

STeVe


Completely off topic, but I just cannot resist showing off.
Some time ago I used __subclasses__ in a way that is not evil. I think.

The details are described in the following thread:
http://groups.google.nl/group/comp.l...ccb986c66cdc1/

A summary: I used __subclasses__ to apply the Chain-of-Responsibility
pattern to object creation. The code would appear to instantiate
an object of the root of a class hierarchy, but the actual object
that was created would be an instance of a subclass.

So to get back to your question: yes, there are non-evil
uses for __subclasses__. Weird perhaps, but non-evil.
Non-standard, sure . Too clever for my own good, very likely.

Regards,

Ruud

--
Ruud de Jong

'@'.join('.'.jo in(s) for s in (['ruud','de','jo ng'],['tiscali','nl']))
Jul 19 '05 #16
Ruud de Jong wrote:
Steven Bethard schreef:
But unless the person eval-ing your code *only* writes immaculate
code I can see that you can probably screw them. ;) I wonder why
__subclasses__ isn't a restricted attribute... Is it ever used for
something that isn't evil? ;)

STeVe


Completely off topic, but I just cannot resist showing off.
Some time ago I used __subclasses__ in a way that is not evil. I
think.

The details are described in the following thread:
http://groups.google.nl/group/comp.l...ead/thread/5c1
ccb986c66cdc1/

A summary: I used __subclasses__ to apply the Chain-of-Responsibility
pattern to object creation. The code would appear to instantiate
an object of the root of a class hierarchy, but the actual object
that was created would be an instance of a subclass.

So to get back to your question: yes, there are non-evil
uses for __subclasses__. Weird perhaps, but non-evil.
Non-standard, sure . Too clever for my own good, very likely.


I've done almost exactly the same thing. The base class uses __subclasses__
to find the best matching subclass based on the factory parameters. In my
case I was retrieving files from the web, so I had a base Handler class and
created HtmlHandler, ImageHandler &c.

class Handler(object) :
'''Class to process files'''
__map = {}

@classmethod
def _resolveClass(k lass, isdir, name):
map = Handler.__map
if not map:
for c in klass.__subclas ses__():
for ext in c.Extensions:
map['.'+ext.lower()] = c

if isdir:
klass = FolderHandler
else:
ext = os.path.splitex t(name)[1].lower()
if ext not in map:
map[ext] = DefaultHandler

klass = map[ext]
return klass(name)

@classmethod
def fromPathname(kl ass, name, path, uri, db):
isdir = os.path.isdir(o s.path.join(pat h, name))
obj = klass._resolveC lass(isdir, name)
obj._initialize (name, path, uri, db)
return obj

@classmethod
def fromUrl(klass, uri, text, db=None):
... and so on ...

and then subclasses such as:

class ImageHandler(Ha ndler):
Extensions = ('jpg', 'jpeg', 'gif', 'png')
type = 'Image'

class DefaultHandler( Handler):
Extensions = ('',)
type = 'Ignored'

This also contains the only code I think I've written with a class
definition in a for loop:

# General categories
EXTENSIONS = {
'js': 'javascript',
'php': 'php',
'doc': 'Word Document',
'xls': 'Spreadsheet',
'ppt': 'Powerpoint',
'css': 'Stylesheet',
'swf': 'Flash',
'pdf': 'File',
'rtf': 'File',
'zip': 'File',
}

Classes = []
for ext in EXTENSIONS:
class GeneralHandler( Handler):
Extensions = (ext,)
type = EXTENSIONS[ext]

Classes.append( GeneralHandler)
Jul 19 '05 #17

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

Similar topics

3
18205
by: Lukas Kasprowicz | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Folks, My Proglem is, I get after a query on a mysql database with module MySQLdb a tuple but I need this output from database as a string. can anybody help? - -------------- database ---------
1
10869
by: Michal Mikolajczyk | last post by:
Is there a quick way to convert a unicode tuple to a tuple containing python strings? (u'USER', u'NODE', u'HASH', u'IDNBR') to this: ('USER', 'NODE', 'HASH', 'IDNBR') I need to be able to do this for a lot of tuples, not just one.
2
5578
by: bwooster47 | last post by:
I'm a newcomer to python - what is the best way to convert a list into a function call agruments? For example: list = (2005, 5, 5) date = datetime.date( list ) fails with: TypeError: function takes exactly 3 arguments (1 given)
7
46236
by: querypk | last post by:
how do I convert b is a string b = '(1,2,3,4)' to b = (1,2,3,4)
1
3113
by: Bell, Kevin | last post by:
I'm pulling a range of cells from Excel into a list and the data in Excel is a number or possibly some text like an asterisk. Each member of the list is a com object (I think) and I'm converting them to integers (or to None if not numberic) but my method seems very silly. Is this the best way to go about it? It does exactly what it should, but it seems like a lot of extra BS to convert my object to a string to a float to a rounded...
5
20017
by: Jon Bowlas | last post by:
Hi listers, I wrote this script in Zope some time ago and it worked for a while, but now I'm getting the following error: TypeError: coercing to Unicode: need string or buffer, NoneType found Here's my script: results = context.module_retriever().tuples() # call to ZSQLMethod converted =
2
1801
by: Tim Chase | last post by:
Is there an easy way to make string-formatting smart enough to gracefully handle iterators/generators? E.g. transform = lambda s: s.upper() pair = ('hello', 'world') print "%s, %s" % pair # works print "%s, %s" % map(transform, pair) # fails with a """ TypeError: not enough arguments for format string
8
25792
by: hidrkannan | last post by:
I am reading a set of data from the excel workbook. Data are contained in 2 columns. Column A contains the names and Column B contains values. The issue is the value can be of any type integer, float, string, list or a tuple. When I read the data from a Cell it is read as of data type unicode. I would like to convert the unicode data type to list type if the data I read is of list type and similarly for tuples. Please suggest if this...
0
218
by: dudeja.rajat | last post by:
On Tue, Aug 19, 2008 at 12:40 PM, <dudeja.rajat@gmail.comwrote: Googled and found : s = "v%d.%d.%d.%d" % tuple(version) print s it's working. Result is : v1.2.3.4
0
9647
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9496
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,...
1
10110
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9961
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
8989
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...
0
6745
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
5397
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...
1
4066
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.