473,796 Members | 2,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python and generic programming


Hi,

I wonder, does Python support generic programming paradigm, and to what extent
(I guess, it doesn't do it in full)? And (or) does it move in that direction?
Will we ever see

concept WellAlright:
...

constructs in Python?
Isn't it right time to reserve "concept" as a keyword ;-)
Sincerely yours, Roman Suzi
--
rn*@onego.ru =\= My AI powered by GNU/Linux RedHat 7.3
Jul 18 '05 #1
16 9733
Roman Suzi <rn*@onego.ru > wrote:
I wonder, does Python support generic programming paradigm, and to what extent


It appears to me to support generics at least as well as C++ does. I
just write normal code (no typechecks) and voila, the equivalent of C++
templates (at least). What do you think is missing?
Alex
Jul 18 '05 #2
On Fri, 22 Oct 2004 00:25:28 +0200, Alex Martelli wrote:
Roman Suzi <rn*@onego.ru > wrote:
I wonder, does Python support generic programming paradigm, and to what extent


It appears to me to support generics at least as well as C++ does. I
just write normal code (no typechecks) and voila, the equivalent of C++
templates (at least). What do you think is missing?


The handcuffs.

Jul 18 '05 #3


Alex Martelli wrote:

Roman Suzi <rn*@onego.ru > wrote:
I wonder, does Python support generic programming paradigm, and to what extent


It appears to me to support generics at least as well as C++ does. I
just write normal code (no typechecks) and voila, the equivalent of C++
templates (at least). What do you think is missing?

Alex


How about specialization? I'm relatively new to Python. I ask for
information, not to be argumentative.

If you have, for example, several data-types for matrices, how do you
write code that will automatically find the right routine for quickly
multiplying a vector by a diagonal matrix represented as a vector, and
automatically call the right code for multiplying by a sparse matrix
represented by some sparse coding, etc?
Jul 18 '05 #4

"Jive Dadson" <jd*****@yahoo. com> wrote in message
news:41******** *******@yahoo.c om...
How about specialization? I'm relatively new to Python. I ask for
information, not to be argumentative.

If you have, for example, several data-types for matrices, how do you
write code that will automatically find the right routine for quickly
multiplying a vector by a diagonal matrix represented as a vector, and
automatically call the right code for multiplying by a sparse matrix
represented by some sparse coding, etc?


Specialization goes in special methods -- the ones named __xxx__ -- of
which there are now 50-100. For each pair of classes, at least one of the
two must know how to do xxx on the other. There is no way to get around
the n square problem, but Python pushes it into individual operations so
you only need one function that uses the operation. So planning is
required for a system of user-defined classed such as multiple matrix
implementations .

For more, see the ref manual and the section on user classes. Also check
'special methods' in the index.

Terry J. Reedy

Jul 18 '05 #5
Jive Dadson wrote:
If you have, for example, several data-types for matrices, how do you
write code that will automatically find the right routine for quickly
multiplying a vector by a diagonal matrix represented as a vector, and
automatically call the right code for multiplying by a sparse matrix
represented by some sparse coding, etc?


I haven't been following this thread, but Phillip Eby's recent
implementation of generic functions should be mentioned if it hasn't
been already:

http://dirtsimple.org/2004/11/generi...ve-landed.html

It might look something like this:

@dispatch.on('m 1', 'm2')
def matrix_mul(m1, m2):
"Multiply two matrices"

@matrix_mul.whe n(VectorMatrix, SparseMatrix)
def matrix_mul_spar se(m1, m2):
"Special implementation"
--
Ian Bicking / ia**@colorstudy .com / http://blog.ianbicking.org
Jul 18 '05 #6
>>>>> "Terry" == Terry Reedy <tj*****@udel.e du> writes:

Terry> Specialization goes in special methods -- the ones named
Terry> __xxx__ -- of which there are now 50-100. For each pair of
Terry> classes, at least one of the two must know how to do xxx on
Terry> the other. There is no way to get around the n square
Terry> problem, but Python pushes it into individual operations so
Terry> you only need one function that uses the operation. So
Terry> planning is required for a system of user-defined classed
Terry> such as multiple matrix implementations .

No, you don't quite understand what the OP is asking for. C++
templates are function or classes that is parameterized by some
arguments, the parameters can either be integer constants or type
names. So by writing a single template function you create (or
actually, you ask the compiler to create on-the-fly) many functions.
Upon using the parameterized function or class, the compiler will
choose/create the function or class for you. Specialization is a
mechanism that allows you to create a function that overrides the
implementation for some specific parameters. E.g., you can create a
"factorial" function as a template function:

template <int n>
int factorial() { return n * factorial<n-1>(); }

so that when asked, the compiler generates factorial<5>() as a
function which returns 5*factorial<4>( ); factorial<4>() as a function
which returns 4*factorial<3>( ), and so on. The terminal condition is
defined using a specialization:

template <>
int factorial<0>() { return 1; }

When the compiler wants to generate factorial<0>(), the more
specialized form is used, which stops the recursion. In this way you
create a compile-time computed factorial function. During compilation
the optimizer will turn it into a constant, so no computation is done
during run-time: factorial<10>() is in every conceivable way an
integer constant 3628800.

Another example is in the standard library: it defines a vector, which
is a resizable array for specific type (e.g., ints or strings)
normally. So a vector<int> will keep an int*, pointing to an array of
ints, used to hold the integers; and vector<string> will keep a
string*, pointing an array of strings. But if the specific type is
"bool", a bit-vector is created instead (i.e., an int* is used
instead, each int holds 32 values).

I don't see Python supporting generic program in the way C++ does, as
it does so little thing during "compile time" (which is just to
byte-compile the program). What I miss most is a mechanism that
allows programmers to define dispatching of functions based on types,
in a way that does not requires the programmer to specify how to do
dispatching (the compiler will figure it out by itself). I think
there's a PEP for that, though.

Regards,
Isaac.
Jul 18 '05 #7
> No, you don't quite understand what the OP is asking for. C++
templates are function or classes that is parameterized by some
arguments, the parameters can either be integer constants or type
names. So by writing a single template function you create (or
actually, you ask the compiler to create on-the-fly) many functions.
Upon using the parameterized function or class, the compiler will
choose/create the function or class for you. Specialization is a
mechanism that allows you to create a function that overrides the
implementation for some specific parameters. E.g., you can create a
"factorial" function as a template function:

template <int n>
int factorial() { return n * factorial<n-1>(); }

so that when asked, the compiler generates factorial<5>() as a
function which returns 5*factorial<4>( ); factorial<4>() as a function
which returns 4*factorial<3>( ), and so on. The terminal condition is
defined using a specialization:

template <>
int factorial<0>() { return 1; }

When the compiler wants to generate factorial<0>(), the more
specialized form is used, which stops the recursion. In this way you
create a compile-time computed factorial function. During compilation
the optimizer will turn it into a constant, so no computation is done
during run-time: factorial<10>() is in every conceivable way an
integer constant 3628800.


You should mention that C++ lacks the possibility to properly solve
type-equations, so that your provided positive example backfires in cases
where two or more type arguments are needed. An example would be a generic
vector class, that takes the scalar type as argument as well as the
dimension. now for example the multiplying code looks like this:

template <T, N>
void mult(vector<T, N> a, vector<T, N> b) {
a[N] = a[N] * b[N];
mult<T, N-1>(a,b);
}

Now to stop code generation at N=0, you need to write

template <double, 0>
void mult(vector<dou ble, 0> a, vector<double, 0> b) {
a[0] = a[0] * b[0];
}
The above examples are right out of my head, so I can't guarantee they work.

The important thing to observe is that one needs to instantiate the
recursion abortion for the scalar class as well as the dimension 0 - it
won't work like this:

template <T, 0>
void mult(vector<T, 0> a, vector<T, 0> b) {
a[0] = a[0] * b[0];
}

So forgetting to instantiate the used scalar template - for int as example -
will lead to a compiler error, as it tries to generate templates until it
hits the built-in iteration limit.

In functional languages, these things work better, as their pattern-matching
has a notion of "more specialized" patterns over lesser specialized ones.

--
Regards,

Diez B. Roggisch
Jul 18 '05 #8

"Isaac To" <ik****@netscap e.net> wrote in message
news:87******** ****@sinken.loc al.csis.hku.hk. ..
"Terry" == Terry Reedy <tj*****@udel.e du> writes:
Terry> Specialization goes in special methods -- the ones named
Terry> __xxx__ -- of which there are now 50-100.
No, you don't quite understand what the OP is asking for.


No, YOU are the one who does not understand, because you apparently did not
do me the courtesy of reading my entire post, in which I quoted the
question I answered. Here again is the OP's question about *type*
specialization *in Python*:
If you have, for example, several data-types for matrices, how do you
write code that will automatically find the right routine for quickly
multiplying a vector by a diagonal matrix represented as a vector, and
automatically call the right code for multiplying by a sparse matrix
represented by some sparse coding, etc?


The has NOTHING to do with writing base cases in recursive C++ template
metaprogramming (which, ironically, uses the compiler as an interpreter).

Although there may be other answers now and in the future, the answer I
gave is the straightforward standard answer for Python today.

Terry J. Reedy

Jul 18 '05 #9
I take it the ampersand is a neologism in 2.4?

Jive

jdadson at yahoo dott com

"Ian Bicking" <ia**@colorstud y.com> wrote in message
news:ma******** *************** *************** @python.org...
Jive Dadson wrote:
If you have, for example, several data-types for matrices, how do you
write code that will automatically find the right routine for quickly
multiplying a vector by a diagonal matrix represented as a vector, and
automatically call the right code for multiplying by a sparse matrix
represented by some sparse coding, etc?


I haven't been following this thread, but Phillip Eby's recent
implementation of generic functions should be mentioned if it hasn't
been already:

http://dirtsimple.org/2004/11/generi...ve-landed.html

It might look something like this:

@dispatch.on('m 1', 'm2')
def matrix_mul(m1, m2):
"Multiply two matrices"

@matrix_mul.whe n(VectorMatrix, SparseMatrix)
def matrix_mul_spar se(m1, m2):
"Special implementation"
--
Ian Bicking / ia**@colorstudy .com / http://blog.ianbicking.org

Jul 18 '05 #10

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

Similar topics

226
12718
by: Stephen C. Waterbury | last post by:
This seems like it ought to work, according to the description of reduce(), but it doesn't. Is this a bug, or am I missing something? Python 2.3.2 (#1, Oct 20 2003, 01:04:35) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d1 = {'a':1} >>> d2 = {'b':2} >>> d3 = {'c':3}
11
3707
by: Maxim Khesin | last post by:
Hi, being recently introduced to the joys of programming in a powerful dynamic language (go snake!) I periodically rethink which parts of C++ I still miss. One thing I really enjoy is the generics of C++ - i think they are the single strong benefit of a strongly typed system. I was wondering about the possibility of implementing STL-like algorithms in Python and the one thing that I cannot think of doing without a kludge is the object...
42
4114
by: Fred Ma | last post by:
Hello, This is not a troll posting, and I've refrained from asking because I've seen similar threads get all nitter-nattery. But I really want to make a decision on how best to invest my time. I'm not interested on which language is better in *general*, just for my purpose. My area of research is in CAD algorithms, and I'm sensing the need to resort to something more expedient than C++, bash scripting, or sed scripting.
44
2540
by: Iwan van der Kleyn | last post by:
Please ignore if you are allergic to ramblings :-) Despite a puritan streak I've always tried to refrain from language wars or syntax bickering; call it enforced pragmatism. That's the main reason why I've liked Python: it's elegant and simple and still dynamic and flexible. You could do worse for a clean and pragmatic language. I do know my Smaltalk from my Common Lisp and my Ruby from my C#, so I think I'm quite capable of escaping...
63
5190
by: Davor | last post by:
Is it possible to write purely procedural code in Python, or the OO constructs in both language and supporting libraries have got so embedded that it's impossible to avoid them? Also, is anyone aware of any scripting language that could be considered as "Python minus OO stuff"? (As you can see I'm completely new to Python and initially believed it's a nice&simple scripting language before seeing all this OO stuff that was added in over...
2
4455
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c */ #include <time.h>
6
5379
by: metaperl | last post by:
Hello, I am responsible for converting 30 loosey-goosey Perl scripts into 30 well-documented easy to understand and use Python scripts. No one has said anything in particular about how this should be done, but the end product should be "professional" looking. So, I'm looking for some books and suggestions which will help me write high-quality scripts. I know about object-oriented programming and application configuration and have spent...
0
2510
by: metaperl | last post by:
A Comparison of Python Class Objects and Init Files for Program Configuration ============================================================================= Terrence Brannon bauhaus@metaperl.com http://www.livingcosmos.org/Members/sundevil/python/articles/a-comparison-of-python-class-objects-and-init-files-for-program-configuration/view
206
8377
by: WaterWalk | last post by:
I've just read an article "Building Robust System" by Gerald Jay Sussman. The article is here: http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf In it there is a footprint which says: "Indeed, one often hears arguments against building exibility into an engineered sys- tem. For example, in the philosophy of the computer language Python it is claimed: \There should be one|and preferably only one|obvious...
0
9528
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
10456
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...
0
10230
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10174
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
10012
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
9052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6788
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5442
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
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.