Python "with"
Laurent Pointal
laurent.pointal at limsi.fr
Mon Sep 17 07:33:28 EDT 2007
Ivan Voras a écrit :
> Laurent Pointal wrote:
>
>> The ugly part is the 'tmp' name, try to choose a name with a proper
>> meaning about what it is really, and it become clean and readable:
>>
>> filerefs = some.big.structure.or.nested.object.with.file.references
>> filerefs.encoding = "utf-8"
>> filerefs.name = "MyFileName.txt"
>> filerefs.use_quotes = True
>>
>> Isn't it ?
>
> Well, no, but this might be due to personal tastes. At least, I don't
> think it's better then some other alternatives. For example, in C99 you
> can do:
>
> static struct option_s foo_option = {
> .name = "foo",
> .type = O_STRING,
> .def_value = "default"
> };
>
> At least to me, this looks even better than the Pascal's syntax.
If its at construction time, you can do the same with Python:
class option_s(object) :
def __init__(self,**initializers) :
self.__dict__.update(initializers)
foo_option = option_s(
name = "foo",
type_ = O_STRING,
def_value = "default"
)
And if the class has no such construction idiom, you can play like this:
x = X()
x.__dict__.update(dict(
name = "foo",
type_ = O_STRING,
def_value = "default"
))
Note: this directly manipulate objects attributes - some times its
preffered to use ad-hoc methods.
Note2: I prefer the "namespace.name = value" solution, more readable.
Note3: Its funny to see how Python users tries to change the language,
does this occure with C, C++, Java, C# ?
More information about the Python-list
mailing list