Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7945737
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T00:57:35+00:00 2026-06-04T00:57:35+00:00

I am experimenting with ways to implement a simplified Term Rewriting System (TRS)/Symbolic Algebra

  • 0

I am experimenting with ways to implement a simplified Term Rewriting System (TRS)/Symbolic Algebra System in Python.
For this I would really like to be able to be able to intercept and modify the operands in particular cases during the class instance instantiation process.
The solution I came up with, was to create a metaclass that modifies the typical call behavior of a class object (of type ‘type’).

class Preprocess(type):
    """
    Operation argument preprocessing Metaclass.
    Classes using this Metaclass must implement the 
        _preprocess_(*operands, **kwargs)
    classmethod.
    """

    def __call__(cls, *operands, **kwargs):
        pops, pargs = cls._preprocess_(*operands, **kwargs)
        return super(Preprocess, cls).__call__(*pops, **pargs)

An example case would be to expand out nested operations F(F(a,b),c)–>F(a,b,c)

class Flat(object):
    """
    Use for associative Operations to expand nested 
    expressions of same Head: F(F(x,y),z) => F(x,y,z)
    """
    __metaclass__ = Preprocess
    @classmethod
    def _preprocess_(cls, *operands, **kwargs):
        head = []
        for o in operands:
            if isinstance(o, cls):
                head += list(o.operands)
            else:
                head.append(o)
        return tuple(head), kwargs

So, now this behavior can be realized through inheritance:

class Operation(object):
    def __init__(self, *operands):
        self.operands = operands

class F(Flat, Operation):
    pass

This leads to the desired behavior:

print F(F(1,2,3),4,5).operands
(1,2,3,4,5)

However, I would like to combine several such preprocessing classes and have them process the operands sequentially according to the natural class mro.

class Orderless(object):
    """
    Use for commutative Operations to bring into ordered, equivalent 
    form: F(*operands) => F(*sorted(operands))
    """
    __metaclass__ = Preprocess

    @classmethod
    def _preprocess_(cls, *operands, **kwargs):

        return sorted(operands), kwargs

And this does not seem to work as wanted. Defining a Flat and Orderless Operation type

class G(Flat, Orderless, Expression):
    pass

results in only the first Preprocessing superclass being ‘active’.

print G(G(3,2,1),-1,-3).operands
(3,2,1,-1,-3)

How can I ensure that all Preprocessing classes’ preprocess methods are called before class instantiation?

Update:

I can’t seem to formally answer my question yet due to my status as new stackoverflow user.
So, I believe this is probably the best solution I can come up with:

class Preprocess(type):
    """
    Abstract operation argument preprocessing class.
    Subclasses must implement the 
        _preprocess_(*operands, **kwargs)
    classmethod.
    """

    def __call__(cls, *operands, **kwargs):
        for cc in cls.__mro__:
            if hasattr(cc, "_preprocess_"):
                operands, kwargs = cc._preprocess_(*operands, **kwargs)

        return super(Preprocess, cls).__call__(*operands, **kwargs)

I guess the problem is that super(Preprocess, cls).__call__(*operands, **kwargs) does not traverse the mro of cls as expected.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T00:57:37+00:00Added an answer on June 4, 2026 at 12:57 am

    I think you’re going about this the wrong way; drop the metaclass, use class and method decorators instead.

    For example, define your flat as:

    @init_args_preprocessor
    def flat(operands, kwargs): # No need for asterisks
        head = []
        for o in operands:
            if isinstance(o, cls):
                head += list(o.operands)
            else:
                head.append(o)
        return tuple(head), kwargs
    

    With the init_args_preprocessor decorator turning that function into a class decorator:

    def init_args_preprocessor(preprocessor):
        def class_decorator(cls):
            orig_init = cls.__init__
            def new_init(self, *args, **kwargs):
                args, kwargs = preprocessor(args, kwargs)
                orig_init(self, *args, **kwargs)
            cls.__init__ = new_init
            return cls
       return class_decorator
    

    And now, instead of mixins use decorators:

    class Operation(object):
        def __init__(self, *operands):
            self.operands = operands
    
    @flat
    class F(Operation):
        pass
    

    And you should have no problem combining the class modifiers cleanly:

    @init_args_preprocessor
    def orderless(args, kwargs):
        return sorted(args), kwargs
    
    @orderless
    @flat
    class G(Expression):
       pass
    

    Caveat Emptor: All code above strictly untested.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm experimenting with a few ways of doing this but just thought I'd ask
I'm experimenting with TextArea and inheritance to implement some additional functionality on the protected
I'm experimenting with a tagging system which is a many-to-one relationship. My schema is:
I feel embarrassed to ask this question as I feel like I should already
While experimenting a bit with C++ templates I managed to produce this simple code,
I was experimenting with ways to get rid of some memory leaks within my
I'm experimenting with ways to draw a sinusoidal graph. My widget is only expecting
I have been experimenting with ways to read data from a SQL server as
We're experimenting with various ways to throttle user actions in a given time period
As I was experimenting with JSF 2.0 , i came across a scenario like

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.