how to pass a custom object to re.search?

B

brunovianarezende

Hi,

sorry if this is a faq. I've searched and got no result. I'm willing
to pass a custom object to re.search method, but I'm getting the
error:

TypeError: expected string or buffer

I don't want to make my object to inherit from basestring (nor I know
how to do it...). Then I was left with 'buffer'. I tried to make my
object inherit from types.BufferType and got the error:

TypeError: Error when calling the metaclass bases
type 'buffer' is not an acceptable base type

If I call the function buffer passing an instance of my object I get:

TypeError: buffer object expected

Is it possible to make what I want (to pass a custom object to
re.search)?

regards,
Bruno
 
L

Lawrence Oluyede

Is it possible to make what I want (to pass a custom object to
re.search)?

Try to implement __str__() for your object and provide a string
representation for it.

re.search(str(custom_object))
 
B

brunovianarezende

Try to implement __str__() for your object and provide a string
representation for it.

re.search(str(custom_object))

I've done that (and added __unicode__ too). I only didn't want to, I
want to do:

re.search(custom_object)

so, code that worked before as:

re.search(parentobj.custom_object)

don't have to be changed for:

re.search(str(parentobj.custom_object))

and I'm also curious to know if it is possible to do that... :)
 
L

Lawrence Oluyede

and I'm also curious to know if it is possible to do that... :)

Only if re.search() doesn't check for the type of the argument, which it
seems it does.
 
P

Peter Otten

I've done that (and added __unicode__ too). I only didn't want to, I
want to do:

re.search(custom_object)

so, code that worked before as:

re.search(parentobj.custom_object)

don't have to be changed for:

re.search(str(parentobj.custom_object))

and I'm also curious to know if it is possible to do that... :)

Not without monkeypatching the re module:

import re

_original_compile = re._compile

def _wrapped_compile(*key):
try:
custom_compile = key[0].__compile__
except AttributeError:
return _original_compile(*key)
else:
return custom_compile(*key[1:])

re._compile = _wrapped_compile


class Aaa(object):
def __compile__(self, *args):
return re.compile("[Aa]+")

print re.findall(Aaa(), "a yadda so whaaaat")

Peter
 

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
474,434
Messages
2,571,690
Members
48,796
Latest member
Greg L.

Latest Threads

Top