Python code/function layout - python

I am learning Python and am trying to figure out the best way to structure my code.
Lets say I have a long function, and want to break it up into smaller functions. In C, I would make it a 'static' function at the top level (since that is the only level of functions). I would also probably forward declare it and place it after the now-shortened function that uses it.
Now for Python. In Python, I have the option to create a nested function. Since this new "inner" function is really only a piece of the larger function broken off for readability purposes, and only used by it, it sounds like it should be a nested function, but having this function inside the parent function causes the whole function to still be very long, since no code was actually moved out of it! And especially since the functions have to be fully coded before they are called, it means the actual short function is all the way down at the end of this pseudo-long function, making readability terrible!
What is considered good practice for situations like this?

How about placing the smaller functions in an own file and import that in your main function? You'd have something like:
def main_func():
from impl import a, b, c
a()
b()
c()
I think this approach leads to high readability: You see where the smaller functions come from in case you want to look into them, importing them is a one-liner, and the implementation of the main function is directly visible. By choosing an appropriate file name / location, you can also tell the user that these functions are not intended for use outside of main_func (you don't have real information hiding in Python anyway).
By the way: This question doesn't have one correct answer.

As far as I know, the main advantage of inner functions in Python is that they inherit the scope of the enclosing function. So if you need access to variables in the main function's scope (eg. argument or local variable), an inner function is the way to go. Otherwise, do whatever you like and/or find most readable.
EDIT:
See this answer too.

So what I could understand is that you have a long function like:
def long_func(blah, foo, *args):
...
...
my_val = long_func(foo, blah, a, b, c)
What you have done is:
def long_func(blah, foo, *args):
def short_func1():
...
def short_func2():
...
...
short_func1()
short_func2()
...
...
my_val = long_func(foo, blah, a, b, c)
You have lots more options, I'll list two:
Make it into a class
class SomeName(object):
def __init__(self, blah, foo, *args):
self.blah = blah
self.foo = foo
self.args = args
self.result = None # Might keep this for returning values or see (2)
def short_func1(self):
...
def short_func2(self):
...
def run(self): # name it as you like!
self.short_func1()
self.short_func2()
return self.result # (2) or return the last call, on you
...
my_val = SomeName(foo, blah, a, b, c).run()
Make another module and put the short_funcs into it. Just like flyx has suggested.
def long_func(foo, blah, *args):
from my_module import short_func1, short_func2
short_func1(foo)
short_func2(blah)

The good practice is to keep cycomatic complexity low. This practically means breaking your long function into many smaller functions.
The complexity is measured by the number of if, while, do, for, ?:,
catch, switch, case statements, and operators && and || (plus one) in
the body of a constructor, method, static initializer, or instance
initializer. It is a measure of the minimum number of possible paths
through the source and therefore the number of required tests.
Generally 1-4 is considered good, 5-7 ok, 8-10 consider re-factoring,
and 11+ re-factor now !
I suggest to take this advice, coming from Sonar, a code quality analysis tool. A good way to refactor such code is using TDD. First write unit tests to cover all the execution paths of your current function. After that you can refactor with the peace of mind that the unit tests will guarantee you didn't break anything.
If on the other hand your long function is just long, but otherwise already has a low cyclomatic complexity, then I think it doesn't matter much whether the function is nested or not.

Related

Advantages of Higher order functions in Python

To implement prettified xml, I have written following code
def prettify_by_response(response, prettify_func):
root = ET.fromstring(response.content)
return prettify_func(root)
def prettify_by_str(xml_str, prettify_func):
root = ET.fromstring(xml_str)
return prettify_func(root)
def make_pretty_xml(root):
rough_string = ET.tostring(root, "utf-8")
reparsed = minidom.parseString(rough_string)
xml = reparsed.toprettyxml(indent="\t")
return xml
def prettify(response):
if isinstance(response, str) or isinstance(response, bytes):
return prettify_by_str(response, make_pretty_xml)
else:
return prettify_by_response(response, make_pretty_xml)
In prettify_by_response and prettify_by_str functions, I pass function make_pretty_xml as an argument
Instead of passing function as an argument, I can simply call that function.e.g
def prettify_by_str(xml_str, prettify_func):
root = ET.fromstring(xml_str)
return make_pretty_xml(root)
One of the advantage that passing function as an argument to these function over calling that function directly is, this function is not tightly couple to make_pretty_xml function.
What would be other advantages or Am I adding additional complexity?
This seem very open to biased answers I'll try to be impartial but I can't make any promise.
First, high order functions are functions that receive, and/or return functions. The advantages are questionable, I'll try to enumerate the usage of HoF and elucidate the goods and bads of each one
Callbacks
Callbacks came as a solution to blocking calls. I need B to happens after A so I call something that blocks on A and then calls B. This naturally leads to questions like, Hmm, my system wastes a lot of time waiting for things to happen. What if instead of waiting I can get what I need to be done passed as an argument. As anything new in technology that wasn't scaled yet seems a good idea until is scaled.
Callbacks are very common on the event system. If you every code in javascript you know what I'm talking about.
Algorithm abstraction
Some designs, mostly the behavioral ones can make use of HoF to choose some algorithm at runtime. You can have a high-level algorithm that receives functions that deal with low-level stuff. This lead to more abstraction code reuse and portable code. Here, portable means that you can write code to deal with new low levels without changing the high-level ones. This is not related to HoF but can make use of them for great help.
Attaching behavior to another function
The idea here is taking a function as an argument and returning a function that does exactly what the argument function does, plus, some attached behavior. And this is where (I think) HoF really shines.
Python decorators are a perfect example. They take a function as an argument and return another function. This function is attached to the same identifier of the first function
#foo
def bar(*args):
...
is the same of
def bar(*args):
...
bar = foo(bar)
Now, reflect on this code
from functools import lru_cache
#lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
fib is just a Fibonacci function. It calculates the Fibonacci number up to n. Now lru_cache attach a new behavior, of caching results for already previously calculated values. The logic inside fib function is not tainted by LRU cache logic. What a beautiful piece of abstraction we have here.
Applicative style programming or point-free programming
The idea here is to remove variables, or points and combining function applications to express algorithms. I'm sure there are lots of people better than me in this subject wandering SO.
As a side note, this is not a very common style in python.
for i in it:
func(i)
from functools import partial
mapped_it = map(func, it)
In the second example, we removed the i variable. This is common in the parsing world. As another side node, map function is lazy in python, so the second example doesn't have effect until if you iterate over mapped_it
Your case
In your case, you are returning the value of the callback call. In fact, you don't need the callback, you can simply line up the calls as you did, and for this case you don't need HoF.
I hope this helps, and that somebody can show better examples of applicative style :)
Regards

Passing a variable from one function to another function

I have a function with way to much going on in it so I've decided to split it up into smaller functions and call all my block functions inside a single function. --> e.g.
def main_function(self):
time_subtraction(self)
pay_calculation(self,todays_hours)
and -->
def time_subtraction(self):
todays_hours = datetime.combine(datetime(1,1,1,0,0,0), single_object2) - datetime.combine(datetime(1,1,1,0,0,0),single_object)
return todays_hours
So what im trying to accomplish here is to make todays_hours available to my main_function. I've read lots of documentation and other resources but apparently I'm still struggling with this aspect.
EDIT--
This is not a method of the class. Its just a file where i have a lot of functions coded and i import it where needed.
If you want to pass the return value of one function to another, you need to either nest the function calls:
pay_calculation(self, time_subtraction(self))
… or store the value so you can pass it:
hours = time_subtraction(self)
pay_calculation(self, hours)
As a side note, if these are methods in a class, you should be calling them as self.time_subtraction(), self.pay_calculation(hours), etc., not time_subtraction(self), etc. And if they aren't methods in a class, maybe they should be.
Often it makes sense for a function to take a Spam instance, and for a method of Spam to send self as the first argument, in which case this is all fine. But the fact that you've defined def time_subtraction(self): implies that's not what's going on here, and you're confused about methods vs. normal functions.

explicitly passing functions in python

Out of curiosity is more desirable to explicitly pass functions to other functions, or let the function call functions from within. is this a case of Explicit is better than implicit?
for example (the following is only to illustrate what i mean)
def foo(x,y):
return 1 if x > y else 0
partialfun = functools.partial(foo, 1)
def bar(xs,ys):
return partialfun(sum(map(operator.mul,xs,ys)))
>>> bar([1,2,3], [4,5,6])
--or--
def foo(x,y):
return 1 if x > y else 0
partialfun = functools.partial(foo, 1)
def bar(fn,xs,ys):
return fn(sum(map(operator.mul,xs,ys)))
>>> bar(partialfun, [1,2,3], [4,5,6])
There's not really any difference between functions and anything else in this situation. You pass something as an argument if it's a parameter that might vary over different invocations of the function. If the function you are calling (bar in your example) is always calling the same other function, there's no reason to pass that as an argument. If you need to parameterize it so that you can use many different functions (i.e., bar might need to call many functions besides partialfun, and needs to know which one to call), then you need to pass it as an argument.
Generally, yes, but as always, it depends. What you are illustrating here is known as dependency injection. Generally, it is a good idea, as it allows separation of variability from the logic of a given function. This means, for example, that it will be extremely easy for you to test such code.
# To test the process performed in bar(), we can "inject" a function
# which simply returns its argument
def dummy(x):
return x
def bar(fn,xs,ys):
return fn(sum(map(operator.mul,xs,ys)))
>>> assert bar(dummy, [1,2,3], [4,5,6]) == 32
It depends very much on the context.
Basically, if the function is an argument to bar, then it's the responsibility of the caller to know how to implement that function. bar doesn't have to care. But consequently, bar's documentation has to describe what kind of function it needs.
Often this is very appropriate. The obvious example is the map builtin function. map implements the logic of applying a function to each item in a list, and giving back a list of results. map itself neither knows nor cares about what the items are, or what the function is doing to them. map's documentation has to describe that it needs a function of one argument, and each caller of map has to know how to implement or find a suitable function. But this arrangement is great; it allows you to pass a list of your custom objects, and a function which operates specifically on those objects, and map can go away and do its generic thing.
But often this arrangement is inappropriate. A function gives a name to a high level operation and hides the internal implementation details, so you can think of the operation as a unit. Allowing part of its operation to be passed in from outside as a function parameter exposes that it works in a way that uses that function's interface.
A more concrete (though somewhat contrived) example may help. Lets say I've implemented data types representing Person and Job, and I'm writing a function name_and_title for formatting someone's full name and job title into a string, for client code to insert into email signatures or on letterhead or whatever. It's obviously going to take a Person and Job. It could potentially take a function parameter to let the caller decide how to format the person's name: something like lambda firstname, lastname: lastname + ', ' + firstname. But to do this is to expose that I'm representing people's names with a separate first name and last name. If I want to change to supporting a middle name, then either name_and_title won't be able to include the middle name, or I have to change the type of the function it accepts. When I realise that some people have 4 or more names and decide to change to storing a list of names, then I definitely have to change the type of function name_and_title accepts.
So for your bar example, we can't say which is better, because it's an abstract example with no meaning. It depends on whether the call to partialfun is an implementation detail of whatever bar is supposed to be doing, or whether the call to partialfun is something that the caller knows about (and might want to do something else). If it's "part of" bar, then it shouldn't be a parameter. If it's "part of" the caller, then it should be a parameter.
It's worth noting that bar could have a huge number of function parameters. You call sum, map, and operator.mul, which could all be parameterised to make bar more flexible:
def bar(fn, xs,ys, g, h, i):
return fn(g(h(i,xs,ys))
And the way in which g is called on the output of h could be abstracted too:
def bar(fn, xs, ys, g, h, i, j):
return fn(j(g, h(i, xs, ys)))
And we can keep going on and on, until bar doesn't do anything at all, and everything is controlled by the functions passed in, and the caller might as well have just directly done what they want done rather than writing 100 functions to do it and passing those to bar to execute the functions.
So there really isn't a definite answer one way or the other that applies all the time. It depends on the particular code you're writing.

How do I get around not using global variables and passing too many arguments?

A bit of a complex problem to describe here:
I would like to have a function AB(), which maps one input to another, through an intermediate value. More specifically, the function is made up of two function, let's call A() and B(), which both return dictionaries (ie. A[B[input]] --> result)
This is an example of my current file directory:
packageX/
__init__.py
get_part_of_B_expensively.py
something_that_will_use_convert.py
convert.py
packageA/
__init__.py
get_the_entirety_of_A_expensively.py
In my convert.py I have the following:
import get_part_of_B_expensively
from packageA import get_the_entirety_of_A_expensively
dict_A = packageA.get_the_entirety_of_A_expensively()
def get_B():
result = {}
result = get_part_of_B_expensively() # this is a very expensive operation
result += get_rest_of_B_inexpensively() # shorthand for adding two dictionaries
return result # returns a dictionary
dict_B = get_B() # hence why i call it once outside, and not inside AB()
def AB(input):
return dictA[dictB[input]]
Don't think this is proper since I can't initialize dict_B before defining get_B(), and I want AB()'s only parameter to be input, since I want to abstract its implementation. However, I introduce a few variables globally, mainly dict_B and dictA, and I'm not sure if that's the best way to do it. I can separate get_B() into its own package, but I would still be left calling them somewhere in the global frame. Not sure what the approach to this should be, I want to call A() and B(), which calls a file in the same package) as few times as possible but abstract the function AB().
If this is all your module is doing, I wouldn't say it's that bad to keep it that way. For small scripts that are just manipulating specific data, sometimes using a global is okay, especially if you're using it as read-only. (A lot of the confusing problems with globals arise when you need to mutate them or rebind them.) There are plenty of respectable libraries that have global variables storing various sorts of global parameters, such as customization options loaded from config files, etc.
For a more heavyweight situation, if your task were more complex, you could create a class that basically does this:
class Convert(object):
def __init__(self):
self.A = packageA.get_the_entirety_of_A_expensively()
self.B = getB() # or put get_B's code in here
def AB(self, input):
return self.A[self.B[input]]
converter = Convert()
converter.AB('blah')
This could be overkill if you just need to do one thing, but it's the way to go if you need to parameterize the operation (e.g., if you had multiple A and B dicts that you might need to operate on).

Decorators in Ruby (migrating from Python)

I'm spending today learning Ruby from a Python perspective. One thing I have completely failed to grapple with is an equivalent of decorators. To pare things down I'm trying to replicate a trivial Python decorator:
#! /usr/bin/env python
import math
def document(f):
def wrap(x):
print "I am going to square", x
f(x)
return wrap
#document
def square(x):
print math.pow(x, 2)
square(5)
Running this gives me:
I am going to square 5
25.0
So, I want to create a function square(x), but decorate it so it alerts me as to what it's going to square before it does it. Let's get rid of the sugar to make it more basic:
...
def square(x):
print math.pow(x, 2)
square = document(square)
...
So, how do I replicate this in Ruby? Here's my first attempt:
#! /usr/bin/env ruby
def document(f)
def wrap(x)
puts "I am going to square", x
f(x)
end
return wrap
end
def square(x)
puts x**2
end
square = document(square)
square(5)
Running this generates:
./ruby_decorate.rb:8:in `document': wrong number of arguments (0 for 1) (ArgumentError)
from ./ruby_decorate.rb:15:in `<main>'
Which I guess is because parentheses aren't mandatory and it's taking my return wrap as an attempt to return wrap(). I know of no way to refer to a function without calling it.
I've tried various other things, but nothing gets me far.
Here's another approach that eliminates the problem with conflicts between names of aliased methods (NOTE my other solution using modules for decoration is a good alternative too as it also avoids conflicts):
module Documenter
def document(func_name)
old_method = instance_method(func_name)
define_method(func_name) do |*args|
puts "about to call #{func_name}(#{args.join(', ')})"
old_method.bind(self).call(*args)
end
end
end
The above code works because the old_method local variable is kept alive in the new 'hello' method by fact of define_method block being a closure.
Ok, time for my attempt at an answer. I'm aiming here specifically at Pythoneers trying to reorganize their brains. Here's some heavily documented code that (approximately) does what I was originally trying to do:
Decorating instance methods
#! /usr/bin/env ruby
# First, understand that decoration is not 'built in'. You have to make
# your class aware of the concept of decoration. Let's make a module for this.
module Documenter
def document(func_name) # This is the function that will DO the decoration: given a function, it'll extend it to have 'documentation' functionality.
new_name_for_old_function = "#{func_name}_old".to_sym # We extend the old function by 'replacing' it - but to do that, we need to preserve the old one so we can still call it from the snazzy new function.
alias_method(new_name_for_old_function, func_name) # This function, alias_method(), does what it says on the tin - allows us to call either function name to do the same thing. So now we have TWO references to the OLD crappy function. Note that alias_method is NOT a built-in function, but is a method of Class - that's one reason we're doing this from a module.
define_method(func_name) do |*args| # Here we're writing a new method with the name func_name. Yes, that means we're REPLACING the old method.
puts "about to call #{func_name}(#{args.join(', ')})" # ... do whatever extended functionality you want here ...
send(new_name_for_old_function, *args) # This is the same as `self.send`. `self` here is an instance of your extended class. As we had TWO references to the original method, we still have one left over, so we can call it here.
end
end
end
class Squarer # Drop any idea of doing things outside of classes. Your method to decorate has to be in a class/instance rather than floating globally, because the afore-used functions alias_method and define_method are not global.
extend Documenter # We have to give our class the ability to document its functions. Note we EXTEND, not INCLUDE - this gives Squarer, which is an INSTANCE of Class, the class method document() - we would use `include` if we wanted to give INSTANCES of Squarer the method `document`. <http://blog.jayfields.com/2006/05/ruby-extend-and-include.html>
def square(x) # Define our crappy undocumented function.
puts x**2
end
document(:square) # this is the same as `self.document`. `self` here is the CLASS. Because we EXTENDED it, we have access to `document` from the class rather than an instance. `square()` is now jazzed up for every instance of Squarer.
def cube(x) # Yes, the Squarer class has got a bit to big for its boots
puts x**3
end
document(:cube)
end
# Now you can play with squarers all day long, blissfully unaware of its ability to `document` itself.
squarer = Squarer.new
squarer.square(5)
squarer.cube(5)
Still confused? I wouldn't be surprised; this has taken me almost a whole DAY. Some other things you should know:
The first thing, which is CRUCIAL, is to read this: http://www.softiesonrails.com/2007/8/15/ruby-101-methods-and-messages. When you call 'foo' in Ruby, what you're actually doing is sending a message to its owner: "please call your method 'foo'". You just can't get a direct hold on functions in Ruby in the way you can in Python; they're slippery and elusive. You can only see them as though shadows on a cave wall; you can only reference them through strings/symbols that happen to be their name. Try and think of every method call 'object.foo(args)' you do in Ruby as the equivalent of this in Python: 'object.getattribute('foo')(args)'.
Stop writing any function/method definitions outside of modules/classes.
Accept from the get-go that this learning experience is going to be brain-melting, and take your time. If Ruby isn't making sense, punch a wall, go make a cup of coffee, or take a night's sleep.
Decorating class methods
The above code decorates instance methods. What if you want to decorate methods directly on the class? If you read http://www.rubyfleebie.com/understanding-class-methods-in-ruby, you find there are three methods for creating class methods -- but only one of them works for us here.
That is the anonymous class << self technique. Let's do the above but so we can call square() and cube() without instantiating it:
class Squarer
class << self # class methods go in here
extend Documenter
def square(x)
puts x**2
end
document(:square)
def cube(x)
puts x**3
end
document(:cube)
end
end
Squarer.square(5)
Squarer.cube(5)
Have fun!
Python-like decorators can be implemented in Ruby. I won't try to explain and give examples, because Yehuda Katz has already published a good blog post about decorators DSL in Ruby, so I highly recommend to read it:
Python Decorators in Ruby
Source code and tests
UPDATE: I've got a couple of vote downs on this one, so let me explain further.
alias_method (and alias_method_chain) is NOT exactly the same concept as a decorator. It is just a way to re-define method implementation without using inheritance (so client code won't notice a difference, still using the same method call). It could be useful. But also it could be error-prone. Anyone who used Gettext library for Ruby probably noticed that its ActiveRecord integration has been broken with each Rails major upgrade, because aliased version has been following the semantics of an old method.
The purpose of a decorator in general is NOT to change the internals of any given method and still be able to call the original one from a modified version, but to enhance the function behavior. The "entry/exit" use case, which is somewhat close to alias_method_chain, is only a simple demonstration. Another, more useful kind of a decorator could be #login_required, which checks authorization, and only runs the function if authorization was successful, or #trace(arg1, arg2, arg3), which could perform a set of tracing procedures (and be called with different arguments for different methods decoration).
What you might achieve with decorators in Python, you achieve with blocks in Ruby. (I cannot believe how many answers are on this page, without a single yield statement!)
def wrap(x)
puts "I am going to square #{x}"
yield x
end
def square(x)
x**2
end
>> wrap(2) { |x| square(x) }
=> I am going to square 2
=> 4
The concept is similar. With the decorator in Python, you're essentially passing the function "square" to be called from within "wrap". With the block in Ruby, I'm passing not the function itself, but a block of code inside of which the function is invoked, and that block of code is executed within the context of "wrap", where the yield statement is.
Unlike with decorators, the Ruby block being passed doesn't need a function to be part of it. The above could have been simply:
def wrap(x)
puts "I am going to square #{x}"
yield x
end
>> wrap(4) { |x| x**2 }
=> I am going to square 4
=> 16
This is a slightly unusual question, but interesting. I'd first strongly recommend that you don't try and directly transfer your Python knowledge to Ruby - it's better to learn the idioms of Ruby and apply them directly, rather than try to transfer Python directly. I've used both languages a lot, and they're both best when following their own rules and conventions.
Having said all that, here's some nifty code that you can use.
def with_document func_name, *args
puts "about to call #{func_name}(#{args.to_s[1...-1]})"
method(func_name).call *args
end
def square x
puts x**2
end
def multiply a, b
puts a*b
end
with_document :square, 5
with_document :multiply, 5, 3
this produces
about to call square(5)
25
about to call multiply(5, 3)
15
which I'm sure you'll agree does the job.
IMO mooware has the best answer so far and it is the cleanest, simplest and most idiomatic. However he is making use of 'alias_method_chain' which is part of Rails, and not pure Ruby. Here is a rewrite using pure Ruby:
class Foo
def square(x)
puts x**2
end
alias_method :orig_square, :square
def square(x)
puts "I am going to square #{x}"
orig_square(x)
end
end
You can also accomplish the same thing using modules instead:
module Decorator
def square(x)
puts "I am going to square #{x}"
super
end
end
class Foo
def square(x)
puts x**2
end
end
# let's create an instance
foo = Foo.new
# let's decorate the 'square' method on the instance
foo.extend Decorator
# let's invoke the new decorated method
foo.square(5) #=> "I am going to square 5"
#=> 25
Michael Fairley demonstrated this at RailsConf 2012. Code is available here on Github. Simple usage examples:
class Math
extend MethodDecorators
+Memoized
def fib(n)
if n <= 1
1
else
fib(n - 1) * fib(n - 2)
end
end
end
# or using an instance of a Decorator to pass options
class ExternalService
extend MethodDecorators
+Retry.new(3)
def request
...
end
end
Your guess is right.
You best use alias to bind the original method to another name, and then define the new one to print something and call the old one. If you need to do this repeatedly, you can make a method that does this for any method (I had an example once, but cannot find it now).
PS: your code does not define a function within a function but another function on the same object (yes, this is an undocument feature of Ruby)
class A
def m
def n
end
end
end
defines both m and n on A.
NB: the way to refer to a function would be
A.method(:m)
Okay, found my code again that does decorators in Ruby. It uses alias to bind the original method to another name, and then define the new one to print something and call the old one. All this is done using eval, such that it can be reused like decorators in Python.
module Document
def document(symbol)
self.send :class_eval, """
alias :#{symbol}_old :#{symbol}
def #{symbol} *args
puts 'going to #{symbol} '+args.join(', ')
#{symbol}_old *args
end"""
end
end
class A
extend Document
def square(n)
puts n * n
end
def multiply(a,b)
puts a * b
end
document :square
document :multiply
end
a = A.new
a.square 5
a.multiply 3,4
Edit: here the same with a block (no string manipulation pain)
module Document
def document(symbol)
self.class_eval do
symbol_old = "#{symbol}_old".to_sym
alias_method symbol_old, symbol
define_method symbol do |*args|
puts "going to #{symbol} "+args.join(', ')
self.send symbol_old, *args
end
end
end
end
I believe the corresponding Ruby idiom would be the alias method chain, which is heavily used by Rails. This article also considers it as the Ruby-style decorator.
For your example it should look like this:
class Foo
def square(x)
puts x**2
end
def square_with_wrap(x)
puts "I am going to square", x
square_without_wrap(x)
end
alias_method_chain :square, :wrap
end
The alias_method_chain call renames square to square_without_wrap and makes square an alias for square_with_wrap.
I believe Ruby 1.8 doesn't have this method built-in, so you would have to copy it from Rails, but 1.9 should include it.
My Ruby-Skills have gotten a bit rusty, so I'm sorry if the code doesn't actually work, but I'm sure it demonstrates the concept.
In Ruby you can mimic Python's syntax for decorators like this:
def document
decorate_next_def {|name, to_decorate|
print "I am going to square", x
to_decorate
}
end
document
def square(x)
print math.pow(x, 2)
end
Though you need some lib for that. I've written here how to implement such functionality (when I was trying to find there something in Rython that is missing in Ruby).

Categories

Resources