Class::C3(3)
π NAME π
Class::C3 β a pragma that makes Perl 5 use the C3 method resolution order algorithm. Yes bestie, we're rewriting the inheritance rules, and honestly? It's giving main character energy. π
β¨ SYNOPSIS β¨
okay so before you even look at this code, read the comment, because it matters:
# NOTE - DO NOT USE Class::C3 directly as a user, use MRO::Compat instead!
package ClassA;
use Class::C3;
sub hello { 'A::hello' }
package ClassB;
use base 'ClassA';
use Class::C3;
package ClassC;
use base 'ClassA';
use Class::C3;
sub hello { 'C::hello' }
package ClassD;
use base ('ClassB', 'ClassC');
use Class::C3;
# Classic Diamond MI pattern
# <A>
# / \
# <B> <C>
# \ /
# <D>
package main;
# initializez the C3 module
# (formerly called in INIT)
Class::C3::initialize();
print join ', ' => Class::C3::calculateMRO('ClassD'); # prints ClassD, ClassB, ClassC, ClassA
print ClassD->hello(); # prints 'C::hello' instead of the standard p5 'A::hello'
ClassD->can('hello')->(); # can() also works correctly
UNIVERSAL::can('ClassD', 'hello'); # as does UNIVERSAL::can()
like, the diamond pattern is iconic honestly, and the way ClassD->hello() prints 'C::hello' instead of the standard p5 'A::hello'? that's the whole point, babes. π¦
πΈ DESCRIPTION πΈ
So Class::C3 is a pragma that swaps out Perl 5's standard method resolution order β depth-first left-to-right, a.k.a. pre-order, a.k.a. the old way β for the much more sophisticated C3 method resolution order. Glow-up complete. β¨
NOTE: YOU SHOULD NOT USE THIS MODULE DIRECTLY β the feature it provides is already integrated into perl version >= 5.9.5, and you should useMRO::Compatinstead.MRO::Compatuses the core implementation on newer perls and falls back to this implementation on older ones. so like, respect the ecosystem please. π
π§ What is C3?
C3 is the name of an algorithm whose whole goal is to provide a sane method resolution order under multiple inheritance. It first popped up in the language Dylan (links live in the "SEE ALSO" section, go look), and then it got adopted as the preferred MRO β Method Resolution Order, keep up π β for the new-style classes in Python 2.3. And most recently? It's been adopted as the 'canonical' MRO for Perl 6 classes, and as the default MRO for Parrot objects too. C3 is literally everywhere, no cap.
π¦ How does C3 work.
C3 works by always preserving local precedence ordering. Basically what that means: no class will ever appear before any of its subclasses. Periodt. Take the classic diamond inheritance pattern for instance:
<A>
/ \
<B> <C>
\ /
<D>
The standard Perl 5 MRO would be (D, B, A, C). And see the problem? A shows up before C, even though C is the subclass of A. Rude. The C3 MRO algorithm, however, produces (D, B, C, A) β which does not have this same issue. slay. π
This example is pretty trivial ngl. For more complex examples and a deeper explanation, check the links in the "SEE ALSO" section.
π How does this module work?
This module uses a technique similar to Perl 5's method caching. When Class::C3::initialize is called, this module calculates the MRO of all the classes which called use Class::C3. Then it gathers info from the symbol tables of each of those classes, and builds a set of method aliases for the correct dispatch ordering. Once all these C3-based method tables are created, it adds the method aliases into the local class's symbol table.
The end result? Classes with pre-cached method dispatch. Iconic. π
β οΈ but heads up: this caching does not do well if you start changing your @ISA or messing with class symbol tables. So you should consider your classes to be effectively closed. The CAVEATS section has the full tea.
π OPTIONAL LOWERCASE PRAGMA π
This release also includes an optional module c3 in the opt/ folder. I did not include this in the regular install, since lowercase module names are considered "bad" by some people. But lowkey? I think the code just looks much nicer like this:
package MyClass;
use c3;
This is more clunky:
package MyClass;
use Class::C3;
But hey, it's your choice β that's literally why it's optional, bestie. π«Ά
π₯ FUNCTIONS π₯
β calculateMRO ($class)
Given a $class, this will return an array of class names in the proper C3 method resolution order. easy. π«
β initialize
This must be called to initialize the C3 method dispatch tables β this module will not work if you don't do this. It's advised to do it as soon as possible after loading any classes which use C3. Here's a quick code example:
package Foo;
use Class::C3;
# ... Foo methods here
package Bar;
use Class::C3;
use base 'Foo';
# ... Bar methods here
package main;
Class::C3::initialize(); # now it is safe to use Foo and Bar
This function used to be called automatically for you in the INIT phase of the perl compiler, but that led to warnings if this module was required at runtime. After discussion with my user base (the DBIx::Class folks), we decided that calling this in INIT was more of an annoyance than a convenience. I apologize to anyone this causes problems for (although I would be very surprised if I had any other users other than the DBIx::Class folks). The simplest solution, of course, is to define your own INIT method which calls this function. π
NOTE: Ifinitializedetects thatinitializehas already been executed, it will "uninitialize" and clear the MRO cache first. like it hits undo before it hits go, basically. π
β uninitialize
Calling this function results in the removal of all cached methods, and the restoration of the old Perl 5 style dispatch order β depth-first, left-to-right. we're going back to the old ways, unfortunately. π
β reinitialize
This is an alias for initialize above. same thing, different word, we love a rebrand. β¨
π§ METHOD REDISPATCHING π§
It is always useful to be able to re-dispatch your method call to the "next most applicable method". This module provides a pseudo package along the lines of SUPER:: or NEXT:: which will re-dispatch the method along the C3 linearization. This is best shown with an example:
# a classic diamond MI pattern ...
# <A>
# / \
# <B> <C>
# \ /
# <D>
package ClassA;
use Class::C3;
sub foo { 'ClassA::foo' }
package ClassB;
use base 'ClassA';
use Class::C3;
sub foo { 'ClassB::foo => ' . (shift)->next::method() }
package ClassC;
use base 'ClassA';
use Class::C3;
sub foo { 'ClassC::foo => ' . (shift)->next::method() }
package ClassD;
use base ('ClassB', 'ClassC');
use Class::C3;
sub foo { 'ClassD::foo => ' . (shift)->next::method() }
print ClassD->foo; # prints out "ClassD::foo => ClassB::foo => ClassC::foo => ClassA::foo"
A few things to note. First: we do not require you to add on the method name to the next::method call (this is unlike NEXT:: and SUPER::, which do require that). This helps to enforce the rule that you cannot dispatch to a method of a different name (this is how NEXT:: behaves as well). π
The next thing to keep in mind is that you will need to pass all arguments to next::method. It can not automatically use the current @_. nope. not happening. π«
If next::method cannot find a next method to re-dispatch the call to, it will throw an exception. You can use next::can to see if next::method will succeed before you call it, like so:
$self->next::method(@_) if $self->next::can;
Additionally, you can use maybe::next::method as a shortcut to only call the next method if it exists. The previous example could be simply written as:
$self->maybe::next::method(@_);
There are some caveats about using next::method β see below for those. π
π CAVEATS π
This module used to be labeled as experimental, however it has now been pretty heavily tested by the good folks over at DBIx::Class and I am confident this module is perfectly usable for whatever your needs might be. π
But there are still caveats, so here goes...
π Use of SUPER::.
The idea of SUPER:: under multiple inheritance is ambiguous, and generally not recommended anyway. However, its use in conjunction with this module is very much not recommended, and in fact very discouraged. The recommended approach is to instead use the supplied next::method feature β see more details on its usage above. like, just don't, bestie. π
ββοΈ
π Changing @ISA.
It is the author's opinion that changing @ISA at runtime is pure insanity anyway. However, people do it, so I must caveat. Any changes to the @ISA will not be reflected in the MRO calculated by this module, and therefore probably won't even show up. If you do this, you will need to call reinitialize in order to recalculate all method dispatch tables. See the reinitialize documentation and an example in t/20_reinitialize.t for more information. π
π Adding/deleting methods from class symbol tables.
This module calculates the MRO for each requested class by interrogating the symbol tables of said classes. So any symbol table manipulation which takes place after our INIT phase is run will not be reflected in the calculated MRO. Just as with changing the @ISA, you will need to call reinitialize for any changes you make to take effect.
π Calling next::method from methods defined outside the class
There is an edge case when using next::method from within a subroutine which was created in a different module than the one it is called from. It sounds complicated, but it really isn't. Here is an example which will not work correctly:
*Foo::foo = sub { (shift)->next::method(@_) };
The problem exists because the anonymous subroutine being assigned to the glob *Foo::foo will show up in the call stack as being called __ANON__ and not foo as you might expect. Since next::method uses caller to find the name of the method it was called in, it will fail in this case. π
But fear not, there is a simple solution. The module Sub::Name will reach into the perl internals and assign a name to an anonymous subroutine for you. Simply do this:
use Sub::Name 'subname';
*Foo::foo = subname 'Foo::foo' => sub { (shift)->next::method(@_) };
and things will Just Work. Of course this is not always possible to do, but to be honest, I just can't manage to find a workaround for it, so until someone gives me a working patch this will be a known limitation of this module. π«
π COMPATIBILITY π
If your software requires Perl 5.9.5 or higher, you do not need Class::C3 β you can simply use mro 'c3', and not worry about initialize(), avoid some of the above caveats, and get the best possible performance. See mro for more details. β‘
If your software is meant to work on earlier Perls, use Class::C3 as documented here. Class::C3 will detect Perl 5.9.5+ and take advantage of the core support when available. π¦
π» Class::C3::XS
Okay so this one's a little bonus module, and it's lowkey iconic β¨ β it'll load Class::C3::XS for you if it's installed and you're running a Perl version older than 5.9.5. And like, the optional module just installs itself automatically whenever a C compiler is around, which is a whole vibe because it gives you significant performance improvements π β but bestie, be aware: unlike the natively-built-in 5.9.5+ core support, this one still has all of the same caveats as Class::C3. So it's fast, not magic. π
π CODE COVERAGE π
So back earlier in this module's life, Devel::Cover was reporting 94.4% overall test coverage. Slay. π These days the test suite does some stuff that straight-up breaks under coverage testing, so we can't hand you a fresh number β but it's fair to assume the coverage is still close to that value. Fr fr. πΈ
π SEE ALSO π
π The original Dylan paper
π¦ The prototype Perl 6 Object Model uses C3
<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel/>
π¦ Parrot now uses C3
<http://aspn.activestate.com/ASPN/Mail/Message/perl6-internals/2746631>
<http://use.perl.org/~autrijus/journal/25768>
π Python 2.3 MRO related links
<http://www.python.org/2.3/mro.html>
<http://www.python.org/2.2.2/descrintro.html#mro>
π§ C3 for TinyCLOS
<http://www.call-with-current-continuation.org/eggs/c3.html>
π«Ά ACKNOWLEGEMENTS π«Ά
(yes, that's genuinely how it's spelled up there, we're keeping it, it's part of the lore π)
Big thank-yous, in no particular order but like, very much in order:
- Matt S. Trout β for using this module inside his module
DBIx::Class, finding a whole pile of bugs, and providing fixes. King behavior π - Justin Guenther β for making
next::methodmore robust by handling calls insideevaland anon-subs. Genuinely a lifesaver π - Robert Norris β for adding support for
next::canandmaybe::next::method. Absolute icon β
π AUTHOR π
- Stevan Little,
<stevan@iinteractive.com> - Brandon L. Black,
<blblack@gmail.com>
π COPYRIGHT AND LICENSE π
Copyright 2005, 2006 by Infinity Interactive, Inc.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Periodt. π
π and that's the whole page bestie!! go forth and linearize your hierarchies π β¨
okay so the footer energy: this was perl v5.42.0 and the page is dated 2020-11-10, filed under Class::C3(3) β that's the whole receipt, mwah ππ
π¦ where this page comes from
- opensuse-leap 16.0: perl-Class-C3 0.35-bp160.1.11 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms