I'm having a scoping problem. I have a module called SpecialFile,
which defines:
def open(fname, mode):
return SpecialFile(fname, mode)
class SpecialFile:
def __init__(self, fname, mode):
self.f = open(fname, mode)
...
The problem, if it isn't obvioius, is that the open() call in __init__
no longer refers to the builtin open(), but to the module open(). So,
if I do:
f = SpecialFile.open(name, mode)
I get infinite recursion.
How do I tell my class that I want to refer to the __builtin__ open(),
and not the one defined in the module?
Thanks,
Gary 6 1194 ga**************@yahoo.com wrote: I'm having a scoping problem. I have a module called SpecialFile, which defines:
def open(fname, mode): return SpecialFile(fname, mode)
class SpecialFile:
def __init__(self, fname, mode): self.f = open(fname, mode) ...
[snip] How do I tell my class that I want to refer to the __builtin__ open(), and not the one defined in the module?
import __builtin__
....
self.f = __builtin__.open(fname, mode)
....
STeVe ga**************@yahoo.com wrote: I'm having a scoping problem. I have a module called SpecialFile,
The convention is to use all_lowercase names for modules, and CamelCase
for classes.
which defines:
def open(fname, mode): return SpecialFile(fname, mode)
This shadows the builtin open() function.
class SpecialFile:
Old-style classes are deprecated, please use new-style classes
def __init__(self, fname, mode): self.f = open(fname, mode) ...
The problem, if it isn't obvioius, is that the open() call in __init__ no longer refers to the builtin open(), but to the module open(). So, if I do:
f = SpecialFile.open(name, mode)
I get infinite recursion.
How do I tell my class that I want to refer to the __builtin__ open(), and not the one defined in the module?
You can use Steven's solution, or keep a reference to the builtin open()
function before defining your own open() function:
builtin_open = open
def open(fname, mode):
return SpecialFile(fname, mode):
class SpecialFile(object):
def __init__(self, fname, mode):
self.f = builtin_open(fname, mode)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
On Mon, 13 Mar 2006 21:28:06 -0800, garyjefferson123 wrote: I'm having a scoping problem. I have a module called SpecialFile, which defines:
def open(fname, mode): return SpecialFile(fname, mode)
This is called "shadowing a built-in", and generally speaking it causes
Bad Things To Happen. The secret to avoiding those Bad Things is to not
shadow built-ins. This isn't a hard and fast rule, but as a good general
principle, if you have to ask "How do I avoid this problem?", you
shouldn't be using shadowing.
(Think of it this way: if you have to ask "How do I avoid being horribly
injured when I crash my car into a wall at 90mph?", you shouldn't be
crashing your car into a wall at 90mph. Yes, I know that makes the
bootstrapping problem difficult for those budding stunt men and women who
want to learn, but they generally manage. And most of the time they manage
by not actually crashing their car into a wall at 90mph -- they find a
better way to get the same effect.)
class SpecialFile:
def __init__(self, fname, mode): self.f = open(fname, mode) ...
The problem, if it isn't obvioius, is that the open() call in __init__ no longer refers to the builtin open(), but to the module open().
In your code, open() is not a module, it is a function.
A better technique will be to turn open into a method of the class
SpecialFile, rather than a bare function. That way you keep open() the
built-in function separate from SpecialFile.open().
So, if I do:
f = SpecialFile.open(name, mode)
I get infinite recursion.
I see you are already using an open method. So let me see if I have this
right: you have a function open, plus an open method? Why?
As near as I can tell, you have a function called "open" which returns a
SpecialFile instance. I don't understand why you would want to do that --
it seems like a poor API design to me. But maybe there's something I don't
understand. It looks like you are expecting to do this:
file = open('data.txt', 'r')
# file is now an automatically opened SpecialFile.
This is bad design because it isn't clear that you have done something
special. It *looks* like you have just opened an ordinary file, and unless
you study the entire module, you wouldn't have any clue that in fact you
have opened a SpecialFile instead.
I would handle it like this:
class SpecialFile(object):
def __init__(self, fname, mode='r'):
self.fname = fname
self.mode = mode
def open(self):
self.f = open(self.fname, self.mode)
def close(self):
self.f.close()
def read(self):
return self.f.read()
def write(self, data):
self.f.write(data)
You use it like so:
sf = SpecialFile("hello.txt")
sf.open()
data = sf.read()
sf.close()
(Actually, I wouldn't handle it like this at all, unless a SpecialFile did
things that an ordinary file didn't. But presumably you have something
special in mind.)
This, in my opinion, is a better solution. You don't have to jump through
hoops to get back at the built-in version of open, and the code is
self-documenting: to open a SpecialFile, you ask for a SpecialFile.
--
Steven.
Steven D'Aprano wrote: So, if I do:
f = SpecialFile.open(name, mode)
I get infinite recursion.
I see you are already using an open method. So let me see if I have this right: you have a function open, plus an open method? Why?
SpecialFile is a module. please read the posts you reply to, and please cut out
the "holier than thou" design advice.
overriding builtins is perfectly okay, if it makes sense for the target application.
just remember to use __builtin__ (a module) instead of __builtins__ (a cpython
implementation hack) if you need to access the original builtins.
</F>
Steven D'Aprano wrote: On Mon, 13 Mar 2006 21:28:06 -0800, garyjefferson123 wrote:
I'm having a scoping problem. I have a module called SpecialFile, which defines:
(snip code)
The problem, if it isn't obvioius, is that the open() call in __init__ no longer refers to the builtin open(), but to the module open().
In your code, open() is not a module, it is a function.
Steven, it seems clear that the OP knows that already. Try reading the
previous sentence as:
"""
The problem, if it isn't obvioius, is that the open() call in __init__
no longer refers to the builtin's open(), but to the module's open().
"""
Does it make more sens ?-)
A better technique will be to turn open into a method of the class SpecialFile, rather than a bare function. That way you keep open() the built-in function separate from SpecialFile.open().
So, if I do:
f = SpecialFile.open(name, mode)
I get infinite recursion.
I see you are already using an open method.
There again, you may want to read more carefully: SpecialFile is *also*
the module's name - which, I agree, is not pythonic.
(snip) I would handle it like this:
class SpecialFile(object): def __init__(self, fname, mode='r'): self.fname = fname self.mode = mode def open(self): self.f = open(self.fname, self.mode) def close(self): self.f.close() def read(self): return self.f.read() def write(self, data): self.f.write(data)
You use it like so:
sf = SpecialFile("hello.txt") sf.open() data = sf.read() sf.close()
Small variant, more builtins-open-like, and taking full advantage of
Python's delegation mechanism:
class SpecialFile(object):
def __init__(self, fname, mode='r'):
self.fname = fname
self.mode = mode
self._file = open(self.fname, self.mode)
def __getattr__(self, name):
return getattr(self._file)
which allows:
sf = SpecialFile("hello.txt")
# then use it just like any other file object
My 2 cents
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
"bruno at modulix" wrote: There again, you may want to read more carefully: SpecialFile is *also* the module's name - which, I agree, is not pythonic.
this approach was recommended by the official style until very recently. http://www.python.org/doc/essays/styleguide.html
Modules that export a single class (or a number of closely related
classes, plus some additional support) are often named in Mixed-
Case, with the module name being the same as the class name
(e.g. the standard StringIO module).
</F> This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: John Ladasky |
last post by:
Hi there,
Just wanted to share a frustrating programming bug that, when I
figured it out, made me gasp, and then laugh.
In one of my programs I wrote...
c = max(a,b)
....and I was...
|
by: Bryan Ray |
last post by:
I am trying to write an inheritance function, so I can call a base
classes method that has been overridden in the derived class. I want to
get rid of the ugly 'call()' syntax that would be used....
|
by: Bj?rn Toft Madsen |
last post by:
Hi all,
The network library I use communicates with my app using a callback
function. This callback function is called with the type of message, a
void pointer to he actual message and a user...
|
by: Sean Connery |
last post by:
I have a Microsoft UI Process Application Block that is controlling child
forms in an MDI parent container. The views node in the app.config file has
been set to stayOpen=false.
Because there...
|
by: S. I. Becker |
last post by:
Is it possible to determine if a function has been overridden by an
object, when I have a pointer to that object as it's base class (which
is abstract)? The reason I want to do this is that I want...
|
by: Allan Ebdrup |
last post by:
I'm writing some code where I have have a class that implements 4 methods
(class A)
I only want to call these methods from the base class if they have been
overridden in a sub class (Class B) I...
|
by: CoderHead |
last post by:
I understand what's happening, but not why. I hope somebody else can
help me out.
I wrote a class library - DataAccess. This library can be included in
any type of application but for now is...
|
by: Ratko |
last post by:
Hi all,
I was wondering if something like this is possible. Can a base class
somehow know if a certain method has been overridden by the subclass?
I appreciate any ideas.
Thanks,
Ratko
|
by: wink |
last post by:
I'd like to determine if a method has been overridden as was asked
here:
http://www.velocityreviews.com/forums/t564224-determining-whether-a-derived-class-overrides-a-virtual-memberfunction.html...
|
by: nsphelt |
last post by:
I am wondering if it is possible to access the underlying property of a base class within a derived that has overridden that property. I am using VB.NET and when I use the MyBase keyword to access...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
| |