By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,666 Members | 1,251 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,666 IT Pros & Developers. It's quick & easy.

How to determine number of output arguments in Python? (nargout in MATLAB)

P: 3
Hi guys!

I'm a total newbie in Python. I hope someone could be so kind and help me out here. I'm trying to transfer some MATLAB source codes to Python and run into a problem.

In MATLAB there is a command "nargout" which returns the number of output arguments specified in the call to the currently executing function.
I would like to use similar method for Python in order to decrease the processing time.

The user should be able to choose which output arguments of function he needs and the unchosen one should be ignored and should not be calculated at all. In order to be able to do that, the number of output arguments which user has chosen, need to be determined first. And I absolutely have no idea how to do this.

Example of my code
if the user calls the function like this, all parameters should be calculated and shown.
Expand|Select|Wrap|Line Numbers
  1.  q,r,s = ft(a,b)

But if user calls only "q, r". Then "s" should be ignored and not calculated.

Expand|Select|Wrap|Line Numbers
  1. q,r = ft(a,b)
Could somebody please kindly advise me on how this works?

Thank you very much in advance for every answer!
Mar 20 '12 #1
Share this Question
Share on Google+
3 Replies

Expert Mod 2.5K+
P: 2,851
I don't know of a way to do that in Python. You could create a class with methods to make the various calculations. A method would be called only when you need the calculation it performs. The calls would look something like this:
Expand|Select|Wrap|Line Numbers
  1. obj = Ft(a,b) # create an instance, calculate 'q' and 'r' as attributes
  2. q = obj.q
  3. r = obj.r
  4. s = obj.calcs()
Mar 20 '12 #2

Expert 100+
P: 626
Python generally uses a dictionary to keep track of variables. You can send one dictionary to the function with the variables, and the calculation also if necessary, and return a second dictionary of key="q", "r", and/or "s" pointing to the result of the calculation for that variable.
Expand|Select|Wrap|Line Numbers
  1. def ft(a,b, a_dict):
  2.     for var in ["q", "r", "s"]:
  3.         if var in a_dict:
  5. a_dict={"q":obj.q, "s":obj.calcs}
  6. return_dict=ft(a,b, a_dict) 
Mar 20 '12 #3

P: 3
Thank you so much for both answers!! :) I will try both ways! :D
Mar 21 '12 #4

Post your reply

Sign in to post your reply or Sign up for a free account.