472,989 Members | 2,963 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,989 software developers and data experts.

using dict for data attributes instead of self



Hi ,today i was reading diveinto python book,in chapter 5 it has a very
generic module to get file information,html,mp3s ,etc.

The code of the example is here :
http://diveintopython.org/object_ori...ork/index.html

One thing that i have some doubs is this part :

class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
So why does he wants a dictionary-like base class if he never uses any
dictionary method,except for dict.clear which is not necesary.

--
could be done like this?

class FileInfo():
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self.name = filename

And the FileInfo subclasses could have the specific attributes that belongs
to each file type,for example mp3.

check the link to the full example.
--

The only reason is to have a base class with arbitrary attributes ? so it
can dinamicaly adquire attributes depending of its subclass or something
like that?

Is there a clearer way to do it? Is there any benefits of going this way
that i dont see?

Maybe this is just a dummy example to just show some functionality related
to the chapter? I am a bit confused.

Jul 18 '05 #1
1 1829
On Sun, 31 Oct 2004 03:52:10 -0400, Alexander Kervero <ve******@gmail.com> wrote:


Hi ,today i was reading diveinto python book,in chapter 5 it has a very
generic module to get file information,html,mp3s ,etc.

The code of the example is here :
http://diveintopython.org/object_ori...ork/index.html

One thing that i have some doubs is this part :

class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
So why does he wants a dictionary-like base class if he never uses any
dictionary method,except for dict.clear which is not necesary.
He does use __setitem__ by way of self["name"] = filename, and he overrides __setitem__
in his subclass as a trick to trigger parsing of the file (and using __setitem__ by way of
self[somename]=somevalue some more) and then actually putting "name" and its filename value
in the base class dict. (IMO that __setitem__ subclass override trick is not a good substitute
for defining __init__ in the subclass. I'm surprised to find it.).

BTW, the above was probably written before you could subclass the builtin dict, but now
there's no need to use UserDict in place of dict, AFAIK.
--
could be done like this?
Not exactly. The subclass is needed for all the dict methods that get used implicitly. Plus
the empty () is bad syntax. And what would UderDict.__init__ do with a self that
wasn't even related? class FileInfo():
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self.name = filename
You could tack name on the instance as an attribute. It might not be a bad idea if
there was a risk of name clash with data keys.
And the FileInfo subclasses could have the specific attributes that belongs
to each file type,for example mp3. I'm not sure what you want to do, but for a general framework you probably want to
avoid having to use only python-legal attribute names for things. No problem with
title, artist, genre, etc. But, e.g., artist-rep wouldn't fly. It depends on whether names
come automatically from data, or are just programmer choices.

check the link to the full example.
--

The only reason is to have a base class with arbitrary attributes ? so it
can dinamicaly adquire attributes depending of its subclass or something
like that? No, but the example is very basic. All it does with the base directory ultimately is
list its key=value content, which is unsorted and doesn't show how alternative
subclasses might want to store and format data differently for listing, etc.,
which you could do by giving the subclasses __str__ methods or standardize on
some other method name, which might just show the name=file_path if the base class
method was not overridden. Etc. E.g., they might all have .html methods to generate
html snippets that could be concatenated for a nice listing. And you might have
a base class attribute for verbosity as a general control.

Is there a clearer way to do it? Is there any benefits of going this way
that i dont see? Think of the base class as common infrastructure. In the example it's just
a dict, but a dict is a very general storage mechanism. What it doesn't instrinsically
have is order or duplicate keys, but you can use it to preserve order and allow
duplicates if you need to. However, a list might be more suitable for some things.
A subclass could use lists as additional ways to store info if needed. And they could
be put in the base dict as values for certain keys, or they could be added as attributes,
keeping the base dict use cleanly separated.
Maybe this is just a dummy example to just show some functionality related
to the chapter? I am a bit confused.

Yes, I think it is a limited example, though I don't know the larger context,
only having looked at the page you provided the url for.

It's an example of a base class and one subclass that relates to specific (mp3)
file info, and suggests that other subclasses could be made according to the
same general pattern, but sharing methods of the base class.

Notice the way it will automatically integrate another subclass for another file extension.
E.g., why don't you try writing a Subclass for .py files? The name would be
class PYFileInfo(UserDict): ... since the name comes from prefixing uppercased extension
to FileInfo.

Maybe make it just read one line from the .py file and store
self['firstline']=<whatever the first line was>. You can just copy the MP3FileInfo class
and rework the pieces.

Then you may notice that you've duplicated generic things that you could put into base
class methods. And you'll see what the framework and inheritance is getting at.

You can then run the program with ['mp3','py'] as the file extension list, and see what
happens.

Have fun ;-)

Regards,
Bengt Richter
Jul 18 '05 #2

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

Similar topics

1
by: Thomas Guettler | last post by:
Hi! After unpickling the objects are not the same any more. Is this a bug or feature? import pickle class MyDictContainer(dict): def __init__(self): dict.__init__(self)
2
by: GrelEns | last post by:
hello, i would like if this behaviour can be obtained from python : trap an attributeError from inside a subclassing dict class... (here is a silly examples to explain my question) class...
17
by: Pierre Fortin | last post by:
Hi, Is the following a reasonable generic approach for converting python returned tuples/lists into dicts...? I'm not advocating library functions also return dicts (I'd probably spend more...
5
by: Carlos Ribeiro | last post by:
Hello all, I'm posting this to the list with the intention to form a group of people interested in this type of solution. I'm not going to spam the list with it, unless for occasional and...
6
by: David Rasmussen | last post by:
If I have a collection of dicts like: john = {'id': 1, 'name': "John Cleese", 'year': 1939} graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941} I could store all of them in a list. But...
9
by: sashang | last post by:
Hi I'd like to use metaclasses to dynamically generate a class based on a parameter to the objects init function. For example: class MetaThing(type): def __init__(cls, name, bases, dict,...
12
by: jeremito | last post by:
Please excuse me if this is obvious to others, but I can't figure it out. I am subclassing dict, but want to prevent direct changing of some key/value pairs. For this I thought I should override...
15
by: Jay Tee | last post by:
Hi, I have some code that does, essentially, the following: - gather information on tens of thousands of items (in this case, jobs running on a compute cluster) - store the information as a...
15
by: hofer | last post by:
Hi, Let's take following perl code snippet: %myhash=( one =1 , two =2 , three =3 ); ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest print "$v1\n$v2\n$v2\n"; How...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
3
SueHopson
by: SueHopson | last post by:
Hi All, I'm trying to create a single code (run off a button that calls the Private Sub) for our parts list report that will allow the user to filter by either/both PartVendor and PartType. On...

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.