Reputation: 11803
Is it possible to replace some built-in python types with custom ones?
I want to create something like:
class MyInt(object):
...
__builtin__.int = MyInt
x = 5
Upvotes: 5
Views: 1993
Reputation: 798636
Since you want to write a Pythonesque DSL, you have two options:
Once you have the AST you can go ahead and execute it directly. In either case, look at Python's Language Services for generation and manipulation of the AST.
Upvotes: 2
Reputation: 251383
You seem to be asking if it's possible to override the type that is created when you enter literals. The answer is no. You cannot make it so that x = 5
uses a type other than the built-in int
type.
You can override __builtin__.int
, but that will only affect explicit use of the name int
, e.g., when you do int("5")
. There's little point to doing this; it's better to just use your regular class and do MyInt("5")
.
More importantly, you can provide operator overloading on your classes so that, for instance, MyInt(5) + 5
works and returns another MyInt. You'd do this by writing an __add__
method for your MyInt class (along with __sub__
for subtraction, etc.).
Upvotes: 4
Reputation: 52253
I don't know about replacing the built-ins, but you can certainly create an object that inherits from them, and/or behaves like them. Look up something like inherit from immutable
and you should find answers that show overriding of __new__
, or for the latter option see 'Emulating Numeric Types'
Upvotes: 2