Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #20374
| References | <090e2893-7a1c-4b11-9e45-974ed33e7b77@i18g2000yqf.googlegroups.com> |
|---|---|
| Date | 2012-02-13 14:27 -0800 |
| Subject | Re: Automatic Type Conversion to String |
| From | Chris Rebert <clp2@rebertia.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.5782.1329172035.27778.python-list@python.org> (permalink) |
On Mon, Feb 13, 2012 at 2:01 PM, Bruce Eckel <lists.eckel@gmail.com> wrote:
> I'm creating a class to encapsulate OS paths, to reduce the visual
> noise and typing from the os.path methods. I've got the class and nose
> tests below, and everything works except the last test which I've
> prefixed with XXX:
>
> def XXXtest_should_work(self):
> """
> Produces:
> open(self.p2, 'w').write('')
> TypeError: coercing to Unicode: need string or buffer, Path
> found
> """
> open(self.p2, 'w').write('')
> assert self.p2
>
> Note that I *have* a __str__(self) method to perform automatic
> conversion to string, and I've commented out the __unicode__(self)
> method because it wasn't getting called. The problem appears to be
> that open() does not seem to be calling __str__ on its first argument,
> but instead it appears to want a basestring and this doesn't
> automatically call __str__.
Right. Python is strongly-typed, so it requires a genuine str here (as
opposed to just something that's stringifyable) and doesn't do an
coercion call to str() for you. Just like how str.join() doesn't
automatically call str() on the elements of the list you give it. This
is to prevent silliness like trying to open() e.g. a dict. Your
alternatives are:
- Learn to live with having to write open(str(path_obj))
- Add a .open() method to Path, and use that instead of the open()
built-in function
- Have Path subclass `str` or `unicode`
> I'm trying to write the Path class so I can just hand a Path object
> to, for example, open() and have it produce the path string.
Impossible, short of subclassing `str` or `unicode`.
Cheers,
Chris
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Automatic Type Conversion to String Bruce Eckel <lists.eckel@gmail.com> - 2012-02-13 14:01 -0800
Re: Automatic Type Conversion to String Chris Rebert <clp2@rebertia.com> - 2012-02-13 14:27 -0800
Re: Automatic Type Conversion to String Bruce Eckel <lists.eckel@gmail.com> - 2012-02-13 15:18 -0800
Re: Automatic Type Conversion to String Bruce Eckel <lists.eckel@gmail.com> - 2012-02-13 15:18 -0800
Re: Automatic Type Conversion to String Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2012-02-14 15:26 +0100
Re: Automatic Type Conversion to String Bruce Eckel <lists.eckel@gmail.com> - 2012-02-15 06:58 -0800
Re: Automatic Type Conversion to String Ned Deily <nad@acm.org> - 2012-02-15 19:21 +0100
csiph-web