1

I have a function in a script problem1.py:

def normal_method(target):
    a = np.array(np.arange(1,target))
    divisible_numbers = a[(a%3==0)|(a%5==0)]
    sum_value = np.sum(divisible_numbers)
    print sum_value

While calling this function in an IPython window using ,

import numpy as np
from problem1 import normal_method
%timeit normal_method(100)

It gives me TypeError saying normal_method takes no arguments. But when I paste the function into IPython and then call it using the same statement it works. Any ideas why this occurs?

5
  • 1
    As a side note: repesenting natural_numbers as a you are better off writing divisible_numbers = a[(a%3==0) | (a%5==0)] to avoid the for loop. Commented Aug 9, 2013 at 1:08
  • It could be the fact that problem1.py does not have import numpy as np, could be something strange with IPython error reporting. It would be an issue without IPython. Commented Aug 9, 2013 at 1:14
  • @Ophion The script has the import statement and runs fine when called from the IPython console. It is only when I import the function that it gives the error. Commented Aug 9, 2013 at 1:17
  • I cannot reproduce the issue on OSX, do you have other issues importing functions? Commented Aug 9, 2013 at 1:25
  • So I ran into another issue..if I declare a function as def ihn(): print np.arange(5) and I try to do from problem1 import ihn, it does not even acknowledge ihn. But if I do import problem1, then I can use ihn. Strange! Commented Aug 9, 2013 at 1:35

2 Answers 2

1

Your problem is that the interactive Python is not reloading the module.

Take a look here. You can try:

import problem1
problem1 = reload(problem1)
%timeit problem1.normal_method(10)

Or just run from a command prompt shell:

python test.py

With test.py containing:

import numpy as np
from problem1 import normal_method
%timeit normal_method(100)

This is more robust and should be the prefered method if you are doing multiple imports from different new modules.

Sign up to request clarification or add additional context in comments.

2 Comments

The first method works. I think you meant %timeit problem1.normal_method(10). Can we use %timeit in a script?
yes you are right... you can use timeit in a script, check here for instance...
0

You do not have "import numpy as np" in the problem1.py file, so at the scope of the function definition, the ref to np is invalid, and that error may be making the definition unavailable in the caller.

Once you put the "import numpy as np" in the module file, things so=hould be all right.

1 Comment

I have import numpy as np in my script. I have only posted the function in the post. It seems that there is a delay/load problem in IPython. If you restart IPython and reload the module, it works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.