9

Python seems disallow you to assign attribute to the internal highest level of 'object':

object.lst=lambda o:list(o)

Or

func=lambda o:list(o)
setattr(object,'lst',func)

All generate error messages. Any design reason behind it? Honestly, this is odd, since everything is an object, and you can define func(obj) as you wish, so if func is not constraint the argument type, why the method way is prohibited to add then? obj.func() is exactly func(obj) if you assign the func as an attribute to the object. Since everything is an object,an attribute of the object is a global function almost by definition.

Anyway to walk-around?

Basically if you have the capability to add some functions to build-in types, you can do pipeline style programming:obj.list().len().range() and I think the readibility of this type program is very clear and nothing non-pythonic.

NathaneilCapital
  • 1,389
  • 5
  • 17
  • 23
  • See also: http://stackoverflow.com/questions/6738987/extension-method-for-python-built-in-types – senshin Jan 23 '14 at 21:47
  • @senshin, this add-in do exactly assigning attribute to internal object, if you put it in answer I I can accept it as the answer. – NathaneilCapital Jan 25 '14 at 16:51
  • Please feel free to answer the question yourself - you know what you're looking for better than I do. – senshin Jan 26 '14 at 03:25

1 Answers1

10

I am not sure at the moment at the actual "design" reasoning for this, though there are - but the fact is that object, as some other built-in classes are written in native code (called "built-in") -

Due to the nature these built-in classes are made (their code is usually in C), they do not have a __dict__ attribute themselves, and thus, disallow arbitrary parameter setting.

Function objects had a __dict__ attribute implemented somewhere along the 2.x development cycle, so they can hold arbitrary attributes.

The way to go if you need something that works as an "object" but have arbitrary attributes is to subclass object, and add your attributes there:

class MyObj(object): pass

MyObj.lst = lambda o: list(o)
101
  • 8,514
  • 6
  • 43
  • 69
jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • 1
    Yes, then its return is a list, a build-in type, you can not add method to it (unless you override return into a subclass again, that means you have many many code to type). – NathaneilCapital Jan 23 '14 at 21:56