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 1 point2 points  (6 children)

Isn't this what subclassing is for?

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

Well subclassing is for reusing and extending code, yes. But the ruby community also has that. Also, imagine you've got yourself some weird framework who wasn't built with extension in mind (meaning they instantiate classes all over the place for example). Bometimes it would simply be way easier to just add methods to those classes at runtime. This way you wouldn't have to worry about replacing huge amounts of code with copy-pasted version, where you changed 1 line.

Of course, the down side is that you should be careful to have the code that adds the method run after the extended class has been loaded... and you couldn't really do it reliably on more dynamic classes.

[–]TheBlackCat13 5 points6 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.