looking for way to include many times some .py code from anotherpython code

Martin MOKREJŠ mmokrejs at ribosome.natur.cuni.cz
Tue Mar 8 08:33:09 EST 2005


Diez B. Roggisch wrote:
>>See my post on Mar 2 about "automating assignment of class variables".
>>I got no answers, maybe I wasn't clear enough ... :(
> 
> 
> Seems so - I for example didn't understand it.
> 
> 
>>I need to define lots of variables. The variable names are often
>>identical. The problem is that if I put such a code into a function ...
>>no, I'm not going to pass anything to a function to get it returned back.
>>I just want to get lots of variables assigned, that all. If I put them
>>into module, it get's exectued only once unless I do reload. And I'd have
>>to use: "from some import *", because mainly I'm interrested in assigning
>>to self: self.x = "blah"
>>self.y = "uhm"
> 
> 
> Okay, I try and guess: From your two posts I infer that you want to set
> variables in instances. But you've got lots of these and you don't want to
> write code like this:
> 
> class Foo:
>     def __init__(self, a, b, .....):
>          self.a = a
>          self.b = b
>          ....
> 
> 
> If that is what you want, then this might help you: Put all the values in a

Good guess! ;)

> dictionary - like this:
> 
> my_vals = {"a": 1, "b" : 2, ....}
> 
> There are plenty of other ways to create such a dictionary, but I won't
> digress on that here.
> 
> Now in your class, you pass than dict to your constructor and then simply
> update the instance's __dict__ so that the keys-value-pairs in my_vals
> become attributes:
> 
> class Foo:
> 
>     def __init__(self, my_vals):
>          self.__dict__.update(my_vals)
> 
> foo = Foo(my_vals)
> 
> print foo.a
> 
> -> 1
> 
> Hope this helps,

Sure. Thanks! Would you prefer exactly for this method over the method posted by Kent Johnson
few minutes ago?

Am I so deperately fighting the language? No-one here on the list needs to set hundreds
variables at once somewhere in their code? I still don't get why:

"include somefile.py" would be that non-pythonic so that it's not available, but
I have already two choices how to proceed anyway. Thanks. ;)

Now have to figure out how to assign them easily into the XML tree.

martin



More information about the Python-list mailing list