473,659 Members | 3,494 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why is Python not supporting full derivation of built-in file class?

Greetings,

I'm wondering why the >> operator does not use the write() method of a
class derived from the built-in file class as in DerivedFile below.

In the following example:

- StringFile is just a file-like string accumulation class that can be
used in place of a real file to accumulate strings that would otherwise
be printed. Works fine, can accumulate strings with the >> operator,
but is not a true file.

- DelegatedFile is a new-style class, a true file class, which provides
all the features of a real file through delegation. It also works fine
and can accumulate string with the >> operator.

- DerivedFile is a new-style class that is derived from file. It
behaves like a true file, but the >> operator does not call its write()
method. Why is that?

Is this related to the fact that on object from that class is seen as a
file (as shown at the end of the code session below)?

Is this intended or is it a flaw in the language that is waiting to be
fixed?

import sys
sys.ps2=' ... '; sys.ps1=' >>> '
def hello(stream=No ne): ... if stream is None:
... stream = sys.stdout
... print >> stream, "Bonjour!"
...
# Using a duck-typing to define a class ... # that behaves like a file for writing only.
... class StringFile:
... "A file-like object to accumulate strings"
... # print >> aStringFile works
... def __init__(self):
... self.strings = []
... def write(self, text):
... self.strings.ap pend(text)
... def writelines(self , lines):
... self.strings.ex tend(lines)
...
# Using delegation to file to create a class that ... # extends the built-in file object.
... class DelegatedFile(o bject):
... "A file-like object to accumulate strings"
... # print >> aStringFile works
... def __init__(self, *args):
... self.strings = []
... self._file = file(*args)
... def __getattr__(sel f, name) :
... return getattr(self._f ile, name)
... def write(self, text):
... self.strings.ap pend(text)
... self._file.writ e(text)
... def writelines(self , lines):
... self.strings.ex tend(lines)
... self._file.writ elines(lines)
...
# Using derivation from file to create a class ... # that extends file. But has a flaw in the use of the >> operator!
... class DerivedFile(fil e):
... "A file object that accumulated written strings"
... # print >> a DerivedFile doe NOT work!
... def __init__(self, *args):
... self.strings = []
... file.__init__(s elf, *args)
... def write(self, text):
... self.strings.ap pend(text)
... file.write(self , text)
... # super(DerivedFi le, self).write(tex t)
... def writelines(self , lines):
... self.strings.ex tend(lines)
... file.writelines (self, lines)
... # super(DerivedFi le, self).writeline s(lines)
...
hello() Bonjour! sf = StringFile()
hello(sf)
sf.strings ['Bonjour!', '\n'] dg = DelegatedFile(" temp.txt","w")
hello(dg)
dg.close()
dg.strings ['Bonjour!', '\n'] for line in file("temp.txt" ): print line ...

Bonjour!
df = DerivedFile("te mp2.txt","w")
hello(df)
df.close()
df.strings [] for line in file("temp2.txt "): print line ...

Bonjour!

sf <__main__.Strin gFile instance at 0x008D86C0> dg <__main__.Deleg atedFile object at 0x008D50B0> df <closed file 'temp2.txt', mode 'w' at 0x0087FA28>


--

Pierre Rouleau
Jul 19 '05 #1
2 1450
This issue was discussed in another recent python-list thread, called
"Writing to stdout and a log file".

My second post includes a patch to Python's "fileobject .c" that made the
code that started that thread work, but for reasons I mentioned in that
post I didn't want to push for inclusion of my patch. I didn't check,
but it will probably allow your code to work too.

If you feel differently, then the thing to do is probably to submit the
patch plus a test case to the sf.net patch tracker for python
(sf.net/projects/python, click on "patches". you'll need a sourceforge
account to submit the patch)

Jeff
PS I did allow the Python test suite to run to completion after I wrote
that message. It didn't produce any failures or unexpected skips on my
platform.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFCa89CJd0 1MZaTXX0RAlm7AJ 43s/kOwPqRfcug/I3I1wzqL/QOggCeLzkr
tTXfi52B7wY4Id5 5oeOuGhk=
=9oYm
-----END PGP SIGNATURE-----

Jul 19 '05 #2
Jeff Epler wrote:
This issue was discussed in another recent python-list thread, called
"Writing to stdout and a log file".

My second post includes a patch to Python's "fileobject .c" that made the
code that started that thread work, but for reasons I mentioned in that
post I didn't want to push for inclusion of my patch. I didn't check,
but it will probably allow your code to work too.

If you feel differently, then the thing to do is probably to submit the
patch plus a test case to the sf.net patch tracker for python
(sf.net/projects/python, click on "patches". you'll need a sourceforge
account to submit the patch)

Jeff
PS I did allow the Python test suite to run to completion after I wrote
that message. It didn't produce any failures or unexpected skips on my
platform.


Thanks. I never got involved in Python development before, so I will
take a look at the development process. I took a quick look at the
affected C files and must confess that I need more time looking at them
to learn everything around it. However, I think that the behaviour of
file handling should change so that any class derived from file should
support the >> operator 'properly' (ie the derived class write() method
should be called).

Pierre
Jul 19 '05 #3

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

Similar topics

19
3171
by: Patrick Useldinger | last post by:
Hi all, after my unsuccessful try to run Apache 2 with mod_python and Python 2.3, I am looking for an alternative approach. My aim is to write a small web-based application: Python - the solution must be based / usable on Python 2.3 Portability Targeted plaforms are
7
2029
by: Brad Clements | last post by:
Is anyone interested in purchasing a hardcopy version of the Python 2.4 Library reference? That is, assuming it was NOT a direct print of current html/pdf versions. So, nicely formatted for a printed book (spiral bound probably), with several indexes as appropriate, or perhaps a permutted index. I'm thinking about doing this through lulu.com or cafepress, but it's going to take a lot of work to make a really nice printed version of...
1
2416
by: mfjacobs | last post by:
Hello, I was hoping someone here can help me with a problem I am having with the PyXML extension ( ver 0.8.4) and Python 2.4 Thsi is a brand new build of Python. Build with default .configre options. Python built and installed fine. PyXML built and installed with no complaining but, when I give the commands below it cannot find the module. Obviously Iam missing somehting. Do you have any suggestions where to
3
1608
by: Wells Caughey | last post by:
I am trying to create an XML Schema type definition by deriving from another type definition using restriction. For example suppose my base type was this: <xs:schema <<schema element setup>> > <xs:complexType name="Fruits"> <xs:sequence> <xs:any minOccurs="8" maxOccurs="8"/> </xs:sequence> </xs:complexType>
48
4919
by: meyer | last post by:
Hi everyone, which compiler will Python 2.5 on Windows (Intel) be built with? I notice that Python 2.4 apparently has been built with the VS2003 toolkit compiler, and I read a post from Scott David Daniels where he said that probably the VS2003 toolkit will be used for Python 2.5 again. However, even before the release of Python 2.5, I cannot seem to find many retailers around here that still carry Visual Studio 2003, and some were a...
3
1843
by: gmax2006 | last post by:
Hi, My RedHat Linux installation already has Python 2.3 on it. What is the easiest way to upgrade it to 2.4? I use ActiveState python in Windows. Is it the best distribution for Linux as well? Thank you, Max
113
5255
by: John Nagle | last post by:
The major complaint I have about Python is that the packages which connect it to other software components all seem to have serious problems. As long as you don't need to talk to anything outside the Python world, you're fine. But once you do, things go downhill. MySQLdb has version and platform compatibility problems. So does M2Crypto. The built-in SSL support is weak. Even basic sockets don't quite work right; the socket module...
1
2161
by: metaglossary | last post by:
I'd like use more than 4 GB of memory for a single python process. Is this possible with a 64-bit processor? I'm using a Woodcrest processor, which I presume supports 64-bit addressing. I've installed the "hugemem" kernel distribute by Red Hat. Yet my Python processes get terminated upon using 4 GB of memory (system has 8 GB). What can be done? Below are some stats about the computer. Thank you for any help. Linux...
0
1365
by: john.goodleaf | last post by:
I've just built pyodbc 2.0.58 against freetds and unixodbc. When I attempt to invoke it, either from the test script or from the interpreter, I get: ImportError: build/lib.linux-x86_64-2.5/pyodbc.so: undefined symbol: PyUnicodeUCS2_Resize I'm not quite sure how to go about troubleshooting this. More info: Build is on opensuse 11.0, intel x86_64 from Python 2.5.2. I've also
1
328
by: Guillermo | last post by:
Hi! Is it possible to load the full-text search module for the SQLite version bundled with Python 2.5? I've tested it and the stand-alone SQLite distribution doesn't seem to include it (sqlite.load fts2), nor does Python. I'm on Windows XP.
0
8851
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
8748
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
8628
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
7359
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
6181
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
5650
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
4175
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...
2
1978
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
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.