empty classes as c structs?
Fernando Perez
fperez.net at gmail.com
Sun Feb 6 18:38:46 EST 2005
Steven Bethard wrote:
> The complications with attribute hiding is one of main reasons I've
> tried to minimize the number of methods associated with Bunch...
in order for bunches to be fully useful in general, open contexts, I think that
number of methods should be exactly zero (at least without leading
underscores). Otherwise, as soon as someone loads a config file into a bunch
and they assign randomname_which_you'd_used, the whole thing breaks.
I see two ways to implement additional (needed) functionality into bunches:
1. The class/staticmethod approach. This has clean syntax, though it may make
inheritance issues tricky, I'm not too sure.
2. To break with pythonic convention a bit, and make the public API of Bunch
consist of methods which all start with a leading _. You can even (via
__setattr__ or metaclass tricks) block assignment to these, and state up front
that Bunches are meant to hold public data only in attributes starting with a
letter. I think that would be a reasonable compromise, allowing you to do:
b = Bunch()
b.update = 'yes'
b._update(somedict)
b.copy = 'no'
c = b._copy()
# BUT:
c._update = 'no' ## an exception is raised
etc.
It's not very pretty, and it does break with pythonic convention. But a Bunch
class which simultaneously provides certain non-trivial functionality
(otherwise the usual 'class Bunch:pass' idiom would be enough), while allowing
users to store arbitrarily named attributes in it, is inevitably going to need
to play namespace tricks somewhere.
FWIW, I personally could live with #2 as an acceptable compromise.
Cheers,
f
More information about the Python-list
mailing list