473,738 Members | 4,774 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Anonymous class members

I thought about this problem over the weekend, after long hours of
hacking some metaclasses to allow me to express some real case data
structures as Python classes. I think that this is something with
potential to be useful, but I would like to hear more opinions first.
If this is deemed to be useful, I *may* try to write a PEP for it.
This is not a promise or even a proposal, at this point.

Broadly generalizing, classes in Python have named members stored in
their pravate __dict__. For normal Python code, this is not an issue.
However, some types of data structures do not need named members. For
example, this is a declaration of a simple web page template that
(ab)uses a Python class declaration:

class WebPage:
__metaclass__ = WebPageTemplate

class MyPage(WebPage) :
class header(HtmlHead er):
title = 'My WebPage'
class body(HtmlBody)
H1('Anonymous class members' )
P('This is an example of anonymous class members')

In the example above, MyPage.body contains two anonymous class
members. There are good reasons not to name them. In the case of long
templates, names are arbitrary, and most of the time are not ever
used.

I'm definining anonymous members as anything that is not a def, a
nested class, or a value that wasn't assigned or bound to name.
Everytime an expression is evaluated in the body of a class, and it's
result is *not* bound to a name, then it's value is stored the magic
_anon__ tuple. Methods or functions that return no value store None as
their return value. Named attributes don't store anything.

As a matter of fact, Python already has a related concept in the
implicit naming of the __doc__ docstring. It may or not pose a problem
for this generalization. That's my basic proposal:

class MyClass:
"""the first anonymous member is the doc string"""
"""the second anonymous member is __anon__[0]"""
1.5 # __anon__[1] = 1.5

The docstring would be a special case -- if the first anonymous value
is a string, and iif it's the first statement, then it's stored as the
__doc__ docstring. It could (or not) be copied also at __anon__[0].
I'm not sure about it.

Some ideas and alternatives still unexplored are:

1) store the __anon__ members in the reverse order (the last value is
always at __anon__0;

2) in the case of loops, then anon members would just be stored as generated.

3) instead of the anonymous members, provide the class with an
augmented dict that can store everything that is declared inside the
class: multiple definitions of the same name, anonymous members, etc.
The mapping interface would retrieve only the named values, but an
iterator would be provided to retrieve all members, named and
anonymous, in the order they were declared. (** this is a general
solution for a wider class of applications **)

4) provide the __anon__ feature only if the metaclass creates it with
a __anon__(cls) factory method. By default, *no anonymous members
would be stored*, but if the metaclass provides a __anon__ structure,
then it's used, and passed to new as an extra keyword argument
(metaclass.__ne w__(cls, name, bases, dct, anon=None)).
Another alternative: augmenting the metaclass interface
------------------------------------------------------------------------

Beware: if up to this point I was in true brainstorm mode, now I'm in
a brain-hurricane-season-in-Florida mode. Be warned :-)

One alternative is to change the metaclass interface, in such a way
that it has an opportunity to catch all statements executed in the
class declaration *before* __new__ is called. A new metaclass method
(lets us call it __store__) and a generator interface to the class
definition could be provided. It would work like this:

1) Immediately upon the class declaration, Python knows what metaclass
it has to call. Either the class inherited a metaclass from an
ancestor, or __metaclass__ member is defined in the first line of the
class.

2) Python's internals check the metaclass for the __store__ function.
If it exists, it's called with the following parameters:

__metaclass__._ _store__(cls, name, bases, class_generator )

3) __store__ retrieves definitions from the class_generator as tuples
of the form:

(name, value)

....where name is None for anonymous class members. At this point, the
metaclass can do whatever it pleases. It can change names, discard
values, or insert calculated values of its own.

4) __store__ returns the dict that will be passed to __new__. This
dict can be an augmented version that stores multiple definitions for
the same name, or anonymous values, or whatever is needed for the
particular class..

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #1
0 2065

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

Similar topics

1
1346
by: Julián Albo | last post by:
Hello. Is the following legal code? class Type1 { }; class Type2 { }; class C { public: union {
3
2056
by: Udo Steinberg | last post by:
Hi, The program below stores the 5 unsigned ints a, b, c, x and y in an anonymous union, so that they share storage space with state. Additionally x and y share storage space with nums. The main function displays the address of each of the 5 integers twice, first using the member pointer table "members" and then using an instance of myclass. The results are surprising: the values for x and y are incorrect when using the member pointers.
0
1651
by: Cordell Lawrence | last post by:
Okay guys, We are wondering if this is a bug in Framework 2.0.40607 and looking for some clarification on the issue. Take a look at the folowing code. public delegate bool BoundryTest(int myVal);
5
8732
by: Chris | last post by:
Hi, I don't get the difference between a struct and a class ! ok, I know that a struct is a value type, the other a reference type, I understand the technical differences between both, but conceptually speaking : when do I define something as 'struct' and when as 'class' ? for example : if I want to represent a 'Time' thing, containing : - data members : hours, mins, secs
5
1692
by: cody | last post by:
I have a very funny/strange effect here. if I let the delegate do "return prop.GetGetMethod().Invoke(info.AudioHeader, null);" then I get wrong results, that is, a wrong method is called and I have no clue why. But if I store the MethodInfo in a local variable I works as expected. I do not understand why this is so, shouldn't both ways be semantically equal?
1
2402
by: qwerty2_reverse_iterator | last post by:
Is this a bug with the ms compiler (V7.1)? (It seems so at least.) I get errors when I don't initialize all the const pointer fields of an anonymous union in a struct. Example: //T2.h typedef int Type1; typedef float Type2; struct S1 {
11
9420
by: Dean Shimic | last post by:
void DisplayLines(object state) { for (int i = 0; i < 500; ++i) { int iCopy = i; rtb.BeginInvoke((MethodInvoker)delegate { rtb.AppendText(iCopy + "\n"); }); }
6
6986
by: Gaijinco | last post by:
I have always felt that there are a lot of topics that you learned the facts but you only grasp the matter sometime down the road. For me, two of those topics are inner classes and anonymous classes. I was thinking of a class Agenda. For it I would use a class Person which also uses another class Date for her birthday. When I was modeling Person, I made an atribute to be an object of class Date. Suddenly I thought that maybe it was a...
0
1420
by: Peter Duniho | last post by:
On Mon, 01 Sep 2008 16:14:10 -0700, Blip <blip@krumpli.comwrote: Briefly, an anonymous method is exactly that: a method without a name. When you use the "delegate" keyword to declare an anonymous method, all you're doing is writing a method the same as you would anywhere else, except that it doesn't have a name, and so you have to use it right away rather than being able to refer to it elsewhere. (And I mean that only in the static,...
0
8969
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8788
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9476
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9263
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9208
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4570
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.