Subject Oriented or Refinements with builtin pytho

2019-04-16 04:01发布

问题:

Goal: Extend abitrary classes with roles that are only valid in a certain context.

This works:

# from https://github.com/niccokunzmann/wwp/blob/master/C_builtinTypes.py
from relative import roleOf, useRoles

@roleOf(int)
class NaturalNumber:
    # int gets successor only in this module
    @property
    def successor(self):
        return 1 + self

@roleOf(tuple)
@roleOf(list)
class MyList:
    @property
    def first(self):
        return self[0]

@useRoles
def test():
    # this is possible if we recompile the code objects
    i = 1
    print(type(i))
    assert i.successor == 2
    assert i.successor.successor == 3
    assert isinstance(i, int) # EDIT3 works
    # check for identity
    t = (3,)
    assert t.first == 3
    l = list() 
    l.append(3)
    assert l.first == 3 # this assertion fails
    assert l.first == 2 + 1

if __name__ == '__main__':
    test()

My Problem:

EDIT2: I wrote 100 lines of code for usual python classes to make this work but for builtins I added 250 lines and there is no complete solution in sight.

I can not create custom classes for builtin objects as I can with pure python classes as link:A or link:B. This is because the compiler puts them everywhere:

>>> test.__code__.co_consts
(None, 1, 2, 3, (3,), 3)

I can not do the replacement in code objects with lists because they are built in the code.

These are my questions because I can not estimate it:

  • What are the places I have to look for builtin objects to replace them with wrappers so I can add roles to them?

  • would an C-extension help me patch the attribute lookup so I can make roles for booleans

  • will I need to compile my own python to make this idea work?

  • is there another solution?

EDIT 1

This is one of my Use-cases: 1 .successor.successor == 3. I want to make it easy to have small domains that do not interfer with the whole program = keep classes slim.

For example I want to make numbers callable to create a lambda calculus.

I want to have slim classes and for special use cases I want to extend them by roles so I can call custom functions on them. I the end something between Data-Context-Interaction and Context-Oriented Programming should come out.

回答1:

Can you provide some more information on your use-case? I think you want to look into metaclasses but not sure without more information on your specific needs. And I think there's something wrong or too clever if you want to replace builtins.



回答2:

I think you want to look into Abstract Base Classes:

http://docs.python.org/3/library/abc.html