-1

im trying to modify the behaviour of the 'int' type in Python.

it says

'__new__' is readonly.

Is there a way to do it?

thanks.

user1275011
  • 1,552
  • 1
  • 16
  • 36
  • 1
    Why would you want to do such a thing? What are you hoping to accomplish? – Karl Knechtel Jun 04 '12 at 18:09
  • Im writing a DSL, and im searching how to make constants to return a derived from the built-int type instead of the built-int type. In ruby you cand do it! Please look at this question: http://stackoverflow.com/questions/10857353/ironpython-dsl-casting-constants-to-c-sharp-types – user1275011 Jun 04 '12 at 18:24
  • @user1275011: That's actually a disadvantage of Ruby: Doing such a thing will affect all libraries and modules, so you can't even use the standard library any more. A similar problem in Python is that you can overwrite builtins, e.g. `import __builtin__; __builtin__.len = lambda x: 42` will probably break most of the standard library. Of course you wouldn't do such nonsense, but people might be tempted to do something like `__builtin__.open = io.open`, which might lead to subtle breakage in certain situations. It would be better if such things were impossible in the first place. – Sven Marnach Jun 04 '12 at 18:33
  • I understand, but the problem here is about syntactic sugar. The client requests to get rid of the constant(53) to simply 53. Im asked to achieve that goal no matter what. – user1275011 Jun 04 '12 at 18:44
  • If you're making a DSL, as opposed to a library, then you're going to parse the input. So when you parse an integer literal out of the input, you just create an instance of whatever other type instead. You say you want to use something derived from the built-in int type, so... just do so, as suggested in the accepted answer. :) Except you really shouldn't have any need to implement `__new__` for that class, either. – Karl Knechtel Jun 05 '12 at 10:41
  • I decided to parse the input, but as the changes are not too complex, Im trying to modify the AST. Now im stuck with this issue: http://stackoverflow.com/questions/10890192/ironpython-compile-does-not-accept-ast-object – user1275011 Jun 05 '12 at 15:17

1 Answers1

5

You can't modify a built-in type, but you can derive from it:

 class MyInt(int):
     def __new__(cls, *args):
         # whatever
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841