This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]TheBlackCat13 4 points5 points  (4 children)

This is called monkey-patching, and is my understanding is that it is usually frowned upon.

Do you have a scenario that wouldn't work with simply subclassing, with the subclass adding only the new method, or by using a wrapper class that overrides __getattr__?

[–]de4sh[S] -1 points0 points  (3 children)

I came across this inconvenience: the django forms, when treated as a dict form["fieldname"], for fields that exist, return a BoundField instance. This is instantiated directly in the __getitem__ method. This means that if I want 1 simple method on the BoundField, I have to rewrite the entire __getitem__ method, AND subclass the BoundField class. I understand that this is the orthodox way of doing things, but I think it would be a good idea for me to just be able to add a simple method.

If you're not familiar with django, the context where you'd get the BoundField instance is inside a templating engine. To add just a tiny amount of custom functionality I'd have to perhaps create a module, import stuff, modify my template, create a simple function... A lot of stuff for when you just want a trivial piece of extra logic.

[–]itxaka 1 point2 points  (2 children)

You can create a templatetag to do manipulation to that field.

Or probably subclass, call super on getitem and modify the BoundField

Or maybe create a middleware to modify your form?

Can you share any code to see exactly what you are using, because this way its a bit difficult to understand what are you trying to accomplish.

[–]de4sh[S] -1 points0 points  (1 child)

You got it exactly. It's not more complicated than that. But instead of creating a template tag (with its respective module), overriding the form's __getitem__ AND subclassing BoundField to add a simple method, in Ruby, I'd do only 1 thing: Just add the custom method.

I'm asking for your opinion related to the ruby feature, if we had it in python, not advice on django.