"literal" objects

Donn Cave donn at u.washington.edu
Wed Dec 24 18:23:23 CET 2003

In article <%QbGb.2109$1f6.732 at newssvr25.news.prodigy.com>,
 "Moosebumps" <purely at unadulterated.nonsense> wrote:

> I'm fairly new to Python, and wondering if you can just list a bunch of
> objects as data.  For example, in C you would just do something like this:
> struct
> {
>     int a;
>     float b;
> } mystruct;
> mystruct x = { 3, 5.0f };
> mystruct y = { 5, 15.0f };
> These are just "data".  Obviously in python you could just write an init
> function like this:
> x.a = 3;
> x.b = 5;
> y.a = 5;
> y.b = 15;

Well, strictly speaking I think the obvious init function would
be looking more like self.a = 3, etc.  What you have written is
legal, if not obvious.  (And lose the semicolons!)

> And that would work fine, but the programmer in me says that that's a pretty
> inelegant way to do it.  Why execute code when all you need is to put data
> in the program?

I think the above paragraph may account for the dismissive
responses you have gotten so far.  While your analysis of the
Python model is structurally fairly sound as far as it goes,
your instincts about what is elegant are utterly misguided!
You are not the first person to ever experience this, though.

> A thought that occured to me is that classes are implemented as dictionaries
> (correct?).  So you could have a dictionary like this:
> x = {'a': 3, 'b': 5}
> y = {'a': 5, 'b': 15}
> This would be the __dict__ attribute of an object I suppose.  But I don't
> see anyway to assign it to a variable so you could access them like x.a and
> y.a.  I don't know if this would be a "nice" way to do it or not.

class A:
    def __init__(self):
        self.__dict__.update({'a': 3, 'b': 5})
x = A()
print x.a, x.b

Would it be nice?  No, it would be horrible, unless you had some
very compelling reason to do this, in which case it would be fine.

> Question 2:
> If "subfolder" is a folder under "basefolder", and basefolder contains
> "base.py", and subfolder contains "sub.py", how do I import sub.py into
> base.py?  From what I can tell so far it only works if the files are in the
> same directory.  I need to be able to do this without modifying any
> environment variables or anything.  Because the scripts will be run on many
> different machines and I have no way of automatically configuring them.

import sys
sys.path.insert(0, 'basefolder/subfolder')

   Donn Cave, donn at u.washington.edu

More information about the Python-list mailing list