# code for Matlab-like functions in Python

Page 1 of 1

## 12 Replies - 1914 Views - Last Post: 10 March 2011 - 06:03 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=217350&amp;s=4b9458a651c9c649db54e79712feea13&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Geza

• New D.I.C Head

Reputation: -1
• Posts: 6
• Joined: 19-February 11

# code for Matlab-like functions in Python

Posted 19 February 2011 - 11:15 PM

I often use Matlab, and I like the way you can define functions in it:
```function return_values=function_name(function params)
```

If you would like to have a similar format in Python,
you can use a decorated function with a little script I wrote (see below).
It still needs to be improved, and I welcome constructive comments on this.

Two very simple examples on how to use it:
```from MtFn import returns

@returns('a,b')
def fun(x,y):
a=x+y
b=x-y

@returns('e')
def approximateEulersNumber(steps):
e=1.0
factorial=1
for i in range(1,steps+1):
factorial*=i
e+=1.0/factorial

print fun(1,2)
print approximateEulersNumber(100)

```

Two things that could be improved:
1. You need to add quotes around the names of the return variables.
2. You may get "unused variable" warnings for the return variables.

And finally, the module you can import to be able to use it:

```'''
Created on Feb 11, 2011
Uses code from persistent_locals2 by Pietro Berkes and Andrea Maffezzoli.
@author: Geza Kiss
'''
import sys

class returns:
def __init__(self, sRetVars):
self.lRetVars=[sVar.strip() for sVar in sRetVars.split(',')]
def __call__(self, fnDecorated):
def Mt2PyFn(*args):
def tracer(frame, event, arg):
if event=='return':
try:
self.tRetVars = tuple([frame.f_locals[var] for var in self.lRetVars])
except KeyError as excKey:
raise KeyError("Return value '%s' is not set in function '%s'." % (excKey.args[0], fnDecorated.__name__))
fnPrevTracer=sys.getprofile()
sys.setprofile(tracer)
try:
res=fnDecorated(*args)
finally:
sys.setprofile(fnPrevTracer)
if res is not None:
raise ValueError("You must not return a value explicitly in function '%s'." % (fnDecorated.__name__))
if 1==len(self.tRetVars):
return self.tRetVars[0]
else:
return self.tRetVars
return Mt2PyFn

```

This post has been edited by Geza: 19 February 2011 - 11:24 PM

Is This A Good Question/Topic? 0

## Replies To: code for Matlab-like functions in Python

### #2 Motoma

Reputation: 452
• Posts: 798
• Joined: 08-June 10

## Re: code for Matlab-like functions in Python

Posted 20 February 2011 - 06:19 AM

I guess I am missing the reason why you are using a decoration function rather than just returning the variables you want...

Could you explain the benefit of using a return decorator rather than just returning?

```def fun(x,y):
a=x+y
b=x-y
return a, b

def approximateEulersNumber(steps):
e=1.0
factorial=1
for i in range(1,steps+1):
factorial*=i
e+=1.0/factorial
return e

print fun(1,2)
print approximateEulersNumber(100)

```

### #3 Geza

• New D.I.C Head

Reputation: -1
• Posts: 6
• Joined: 19-February 11

## Re: code for Matlab-like functions in Python

Posted 20 February 2011 - 09:06 AM

Some benefits of this format could be:
- It shows you what the function returns in the function head, and is better than comments in that it ensures that these values are actually returned.
- It could help people avoid the bad practice of returning different values from different points in the function. (Note that you can still use return without parameters to return from anywhere.)
- It is more familiar if you are used to Matlab.

I admit, it is not as nice as the Matlab-way, which would give def ( a, b )=fun(x,y):, and would allow you to copy the function call from its definition. But Python is not going to allow this syntax (TOOWTDI principle), and the above format may still work for some people.

This post has been edited by Geza: 20 February 2011 - 09:07 AM

### #4 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: code for Matlab-like functions in Python

Posted 22 February 2011 - 07:25 AM

I'll be up front, I don't like this lol. You're trying to write matlab code into Python as oppose to just using Python. This is the difference between programming around a language as oppose to programming in one. You're not writing Python code, you're writing matlab code in Python. It's nice to see a new face on the Python board. I sincerely hope that you stay on the board and take part in future dialogs. That being said, I can't see any reason why a respectable Python programmer would want to use this style.

A couple of side notes:
• there's really nothing wrong with returning different variables in different situations so long as it's intuitive.
• The nice thing about a comment with the function head is that other people using your modules can see it simply by typing help(functionName) as oppose to digging around your source code (which might not even be available to them).

This post has been edited by atraub: 22 February 2011 - 07:28 AM

### #5 Geza

• New D.I.C Head

Reputation: -1
• Posts: 6
• Joined: 19-February 11

## Re: code for Matlab-like functions in Python

Posted 22 February 2011 - 02:50 PM

Thanks for your comment. You are definitely right that using Python's built-in functionality often gives more satisfactory results, as e.g. in the case of the help(...) function. And Python is not for writing Matlab code, that is absolutely true.

But I think that if I had not used the word "Matlab", some people might still like this construct for its own sake. Perhaps I should not have, as we get our ideas from all sorts of places anyway.

And if you write some code for yourself, you may not be interested in your own comments (you may not even write them ), but may still appreciate the help of a construct that does some extra checks for you, as my code does.

Moreover, I am not the only one who has created similar decorators, which may help in certain situations.
See e.g. http://wiki.python.o...BAC8-returns.29 .
These are not for everyone to use, and I do not think they will be a part of the Python syntax. Consequently, they will not get such support as native constructs (e.g. the "help" function will not be augmented to handle these).

But I still think that in certain situations, for certain people, these scripts may be useful, including mine. (You may not be among those people.)

Thanks for your reply anyway, it had some really good points.

Géza

This post has been edited by Geza: 22 February 2011 - 02:52 PM

### #6 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: code for Matlab-like functions in Python

Posted 22 February 2011 - 03:52 PM

Haha if someone is too lazy to write comments, why would they bother using your style? Any good programmer writes comments frequently. I would be embarrassed to show a non-trivial program without any comments in it. You may not see the benefit in writing comments, but in large applications, comments are extremely important.

It doesn't matter that you're using Matlab style, the point is, you're not programming in Python. If you hadn't said Matlab I would have assumed you were trying to turn Python into some ugly vb script hybrid. Python Programmers expect Python code when they look at py files; your style would honestly add an extra layer of complexity with absolutely no benefit.

If the style works for you, that's fine. Unfortunately, most other programmers will have no idea why you're using that style and will interpret it as a sign of inexperience or an inability to adapt to new languages.

This post has been edited by atraub: 22 February 2011 - 03:59 PM

### #7 Geza

• New D.I.C Head

Reputation: -1
• Posts: 6
• Joined: 19-February 11

## Re: code for Matlab-like functions in Python

Posted 22 February 2011 - 05:35 PM

Dear Atrub,

This time you drew wrong conclusions about me, which is not the topic of this discussion anyway.
(In case you are interested, I usually write comments into longer pieces of code, appreciate their use, and know and use quite a few programming languages, according to their core syntax; many say that I adopt quite quickly to new things. It is true that I am not a Python programmer, only one who uses the language.)

A few remarks:

Note that you can write comments AND use such decorators, and this adds no complexity to the program (besides the obvious one of needing to get to recognize one new construct).

Note also that several books on programming suggest using self-explanatory constructs and telling variable names instead of adding a lot of comments (which may increase redundancy, and thus be a source of error).

Note also that many people would agree with your previous comment that it is OK to return different variables in different situations as long as it is intuitive, while others argue that the best is to have one return statement at the end of the function. This construct ensures something between the two (being able to return from anywhere, but still return the same variables consistently).

Note also that this is only one of the available decorators available to everyone, and decorators ARE part of the Python syntax, even though they may add an extra layer of complexity to the program.

Note also that this is not "my style", just a construct I made available to those who find it useful.
If noone finds it useful, that is fine with me. As they say, "Don't look a gift horse in the mouth".

P.S. If you answer, please leave my personality out of the discussion, so that we may remain focused on the topic of this discussion, which is programming practice and constructs.
We may belong to groups who disagree on some things, but as I said earlier, I appreciate your ideas and personality. I wish you all the best.

This post has been edited by Geza: 22 February 2011 - 05:42 PM

### #8 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: code for Matlab-like functions in Python

Posted 23 February 2011 - 07:00 AM

Quote

Dear Atrub atraub,

This time you drew wrong conclusions about me, which is not the topic of this discussion anyway.
(In case you are interested, I usually write comments into longer pieces of code, appreciate their use, and know and use quite a few programming languages, according to their core syntax; many say that I adopt quite quickly to new things. It is true that I am not a Python programmer, only one who uses the language.)
The fact that you suggest using this style in one breath and then say "I'm not a Python Programmer" in the next tells everyone at this board a lot about you.

Quote

Note that you can write comments AND use such decorators, and this adds no complexity to the program (besides the obvious one of needing to get to recognize one new construct).
Once again, the complexity is that you're suggesting using a non-standard style when there is no apparent benefit. It really seems to me that you want to spread this style just for the sake of adding bureaucracy to Python programming. There's just no point. It would most likely lead to less efficient code because early exit cases would become more difficult and/or convoluted.

Quote

Note also that several books on programming suggest using self-explanatory constructs and telling variable names instead of adding a lot of comments (which may increase redundancy, and thus be a source of error).
There's a difference between needlessly using decorators and writing self documenting code. If the former helps you accomplish the latter, more power to you.

Quote

Note also that this is only one of the available decorators available to everyone, and decorators ARE part of the Python syntax, even though they may add an extra layer of complexity to the program.
Just because something is allowed in a language doesn't mean that you need to use it every chance you get; when was the last time you saw a respectable C programmer use a goto statement? Python gives you a lot of power, but knowing how to use that power effectively is a mark of experience.

Quote

P.S. If you answer, please leave my personality out of the discussion, so that we may remain focused on the topic of this discussion, which is programming practice and constructs.
We may belong to groups who disagree on some things, but as I said earlier, I appreciate your ideas and personality. I wish you all the best.
These are not personal attacks; this is a discussion about programming. Please try to recognize the difference. All of us have ideas. If you're not willing to accept criticism on those ideas, you probably shouldn't share them.

This post has been edited by atraub: 23 February 2011 - 06:16 PM

### #9 Geza

• New D.I.C Head

Reputation: -1
• Posts: 6
• Joined: 19-February 11

## Re: code for Matlab-like functions in Python

Posted 05 March 2011 - 08:34 PM

atraub, on 23 February 2011 - 02:00 PM, said:

If you're not willing to accept criticism on those ideas, you probably shouldn't share them.

Again, this topic is not about me.

There are a few good web-sites containing rules that can make community life on forums like this better, if they are applied. For example Wikipedia's one:
http://en.wikipedia....pedia:Etiquette

People have also collected the things to keep in mind while making arguments. For example:
http://www.nizkor.or...-authority.html
http://www.nizkor.or...n-practice.html
http://www.nizkor.or...o-ridicule.html
http://www.nizkor.or...l-to-spite.html
http://www.nizkor.or...n-of-proof.html
http://www.nizkor.or...ures/fallacies/
http://www.fallacyfiles.org/

### #10 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: code for Matlab-like functions in Python

Posted 07 March 2011 - 12:08 PM

If you'd like to make a post about the etiquette that you feel DIC users should observe, please do so in the appropriate forum. If you feel that I have violated some policy at DIC or that I have done something so grossly offensive that it transcends policy at DIC, I'd suggest urge you to use the Report button.

If you would like to drop this entire discussion, that's fine by me. However I'm completely open to discuss Matlab-like functions in Python if you feel that there is some benefit that I simply have failed to see. If you feel that my reasons for disliking Matlab-like functions in Python are flawed, then you can explain why. I stand behind my assertions and will not be offended even if though you call them fallacies and claim that I'm a false authority.

This post has been edited by atraub: 08 March 2011 - 07:09 AM

### #11 Geza

• New D.I.C Head

Reputation: -1
• Posts: 6
• Joined: 19-February 11

## Re: code for Matlab-like functions in Python

Posted 10 March 2011 - 05:06 PM

Dear Atraub,

If you read again carefully what I wrote, and your (occasionally implicit) claims about the same, you will sometimes see a difference.

atraub, on 07 March 2011 - 07:08 PM, said:

though you call them fallacies and claim that I'm a false authority.

For example, I did NOT claim this either. Moreover, the expression false authority does not even appear on any of the web-pages that I sent.
(The page that you may have alluded to has a completely different interpretation for me.)

A summary of what I wrote:
- I never argued that this is really "Pythonic" code.
- I did ask for suggestions on improving it in my first post (mainly as a means of learning more on what is possible in Python), which I never got unfortunately.
- I did answers some of your arguments, but never argued about likes and dislikes. (And it is certainly worthwhile to pay attention to the likes and dislikes of experienced Python programmers like yourself. Folks, please do that if in doubt. :-) )
- I did ask you not to use personalities. (Don't you think that personalities remain personalities even if one says that "most other programmers" think that? More on the logic behind this on the web-pages sent earlier.)

It may sometimes be tempting to jump to conclusions about what others think, or what kind of persons they are. The human mind tends to make up for the missing details based on previous experience when not all the details are given (which is almost exclusively the case).
But carefully reconsidering what exactly has been said or written before answering, and giving less credit to one's ideas that are not thoroughly confirmed by those can help to avoid errors.

I hope that my words will not be misinterpreted this time.
If in doubt, please reread - and always assume good faith.

Géza

### #12 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: code for Matlab-like functions in Python

Posted 10 March 2011 - 05:29 PM

Perhaps I misinterpreted this website you linked:

Quote

False Authority
This fallacy is committed when the person in question is not a legitimate authority on the subject. More formally, if person A is not qualified to make reliable claims in subject S, then the argument will be fallacious.

This sort of reasoning is fallacious when the person in question is not an expert. In such cases the reasoning is flawed because the fact that an unqualified person makes a claim does not provide any justification for the claim. The claim could be true, but the fact that an unqualified person made the claim does not provide any rational reason to accept the claim as true.
It stands to reason that I consider myself something of an authority considering that I'm a professional software engineer and given my standing here at DIC. This link speaks of people with a false sense of authority over a subject matter. No one here is naive enough to not realize that you're insulting me.

Clearly, you're no longer interested in continuing the initial discussion on Matlab-Like Functions In Python. I'm not going to sit here and quibble with you like a child as it would only degrade this thread, my reputation, and DIC as a whole. As this discussion is deteriorating rapidly, I think it's time to amputate. Closing thread.

This post has been edited by atraub: 11 March 2011 - 07:12 AM

### #13 Dogstopper

Reputation: 2965
• Posts: 11,222
• Joined: 15-July 08

## Re: code for Matlab-like functions in Python

Posted 10 March 2011 - 06:03 PM

Hey guys. I do feel that somewhere along the road, you did go astray. For that reason, I am keeping this thread closed. However, Geza, I know you may have felt that atraub was being rude. From what I read, he was simply giving his valid help on the topic at hand. Like he said, he is a professional in his field and is a DIC forum leader, so he is very familiar with Internet Etiquette. However, if ever you feel this way again, please let the team know and we will be happy to assess the situation.