Sorry for the very silly question. I am a self-study beginner in python and I am having issues with using a function and calling it. I am coming from a MATLAB background so i was trying to do something similar.
Tools used: Python 2 in a Linux environment
As a test, I created a function that i called prthis (for "print this") within a file called also prthis.py. This function just takes a number as an input, and then outputs two numbers, respectively the same one and its square. I defined it like this:
#----------------------------------------
# content of the file prthis.py
#----------------------------------------
def prthis(x):
y=x*x
nb=x
return (y, nb)
#------------------------------------------
then, within the python prompt, I try to call the newly created prthis function, and I do this:
>>> import prthis
>>> g,t = prthis(7)
The import seems to be succesful, but when I try the function on two outputs variable called g and t , like above, i get the following error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
Perhaps I am too much MATLAB-izing my thinking. Does anyone has a suggestion on how to deal with this?
PS: it's my first question ever on stackexchange, so please could you let me know how to thank/accept valuable answers from other users? I do not wish to look like ungrateful to those who would try to help.
you are importing a module, not the function. If you want to import just the function you could do this:
from prthis import prthis
g,t = prthis(7)
but if you import the full module you have to define the module you are calling the function from as well:
import prthis
g,t = prthis.prthis(7)
you are successfully able to import prthis but this is not the correct way either you should try "from prthis import prthis. Refer this for a better understanding of calling a function.
What does it mean to "call" a function in Python?
Related
So the issues that I am currently hitting is with the use of __import__ and even just the standard import. When importing multiprocessing just the main package it will go through however when I run a simple test to see if everything is working for it. I come across an error, below is the current code that IS NOT working.
__import__('multiprocessing')
def my_function():
print('Hello World')
if __name__ == '__main__':
processd = multiprocessing.Process(target=my_function)
processd.start()
processd.join()
it run it will return the following error:
Traceback (most recent call last):
File "F:\Webserv\Python\MP.py", line 7, in <module>
processd = multiprocessing.Process(target=my_function)
NameError: name 'multiprocessing' is not defined
Is there something I am missing with this?
__import__ is a function, therefore you need to capture its return value:
multiprocessing = __import__('multiprocessing')
The standard way is to use the import statement:
import multiprocessing
This is the preferred way. Do programmatic imports only when you really need them. Furthermore, __import__ should not be used:
Import a module. Because this function is meant for use by the Python
interpreter and not for general use it is better to use
importlib.import_module() to programmatically import a module.
I have two python scripts, one has all functions I have defined (functions.py) and the other only runs those functions (running_functions.py).
I imported the functions into running_functions script using from functions import*
My problem is when I ran running_functions into python console using execfile('running_functions.py') at first worked like a charm, but if I don't close the python session and do some modifications into one function in functions.py (for example changing the number of parameters that getLabels() takes (from 4 to 5)) saved then and then I ran again running_functions.py with the same comand or when I called getLabels() I get the error:
With execfile()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "running_functions.py", line 82, in <module>
predict_labels = getLabels(pred_labels, ids_tr ,labels_tr,filenames_tr, filenames_ts)
TypeError: getLabels() takes exactly 4 arguments (5 given)
Calling the function
>>> predict_labels = getLabels(pred_labels, ids_tr ,labels_tr,filenames_tr, filenames_ts)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: getLabels() takes exactly 4 arguments (5 given)
To get it work again I have to close python session and then run again execfile() or rename functions.py or do little pythons scripts with modified function.
This is very annoying because all the code takes around 10 or 15 minutes and I don't like have a lot of little scripts. So, how can I avoid this error?
I wouldn't like to close every time the session and wouldn't like to use in each function pickle module. Is it wrong the way I imported the functions? And why python returns this error? Sorry for this silly questions
I would recommend skimming over how python imports work. In general it's considered bad practice to use glob imports like from module import *. It's not transparent and makes it difficult to take advantage of reload.
I would recommend rewriting your code to do the following :
import functions
functions.getLabels(...)
and then after you change getLabels or something, you can from the shell run the following :
reload(functions)
and that will re-import your changes without having to restart the python kernel.
I have a vaguely defined function of a class Graph of a module I call gt (it is graph-tool). so i declare g = gt.graph() then want to use g.degree_property_map but do not know how. Therefore I want to see where in code g.degree_property_map or in this case just the function, is defined. How can I find that? I'm working on command line on a vm.
Thanks
For reference the library in question is graph-tool - http://projects.skewed.de/graph-tool/
Also I am currently importing it using from graph_tool.all import * . that is of course somewhat of a problem.
You could use inspect.getsource(gt.Graph.degree_property_map). (You have to import inspect.)
Of course, what you pass into getsource() will change depending on how you imported Graph. So if you used from graphtools.all import *, you'd just need to use inspect.getsource(Graph.degree_property_map).
If you open interactive python (type python and hit ENTER on the command line), you should be able to run the command help(<graph's module name>), then, under the FILE section of the help documentation that is generated, you should see the absolute path to the code you are interested in.
For example, I just ran:
import numpy
help(numpy)
# Returned documentation containing:
# FILE
# /usr/lib/python2.7/dist-packages/numpy/__init__.py
Also,
import my_module # A module I just created that contains the "Line" class
help(my_module)
# Returned documentation containing:
# FILE
# /home/<my user name>/Programming/Python/my_module.py
If it is a normal function (not a builtin, ufunc, etc) you can try using the func_code attribute
For example:
>>> inspect.iscode
<function iscode at 0x02EAEF30>
>>> inspect.iscode.func_code
<code object iscode at 02EB2B60, file "C:\Python27\lib\inspect.py", line 209>
Never mind I just did help(graph_tool) and manually jumped through code. Thanks for the help though!
i had succesfully installed numpy (numpy-1.6.2-win32-superpack-python2.7.exe). But, whenever i try to call any functions i am getting following the error below. Thanks in advance for help.
import numpy as np
if __name__ == "__main__":
k = np.arange(10)
AttributeError: 'module' object has no attribute 'arange'
Echoing one of the comments above (as I just had this problem, over 4 years later):
You probably named your file numpy.py. When trying to load a module, I believe the path checks the current directory first, and thus it isn't found.
For sanity, to check that it really is this issue, you should run the Python REPL (python) and type:
import numpy as np, followed by dir(np)
And you should see all of the actual functions as output.
This might also happen because you probably named your program file numpy.py (i made the same mistake)
try the following:
for x in dir(np):
print x
this should list all methods etc of your import, that way you can see if arange() is available.
you could also try
from numpy import *
and then just try:
print arange(10)
Can't think of much else. Odd that the import does not produce an error if arange is not there.
I have just started learning python version 3 and trying to create a file in python.
I placed the file in all the places which is shown by this set of command.
import sys
sys.path
The file has a simple function something like this
def hello(var):
print("Hello "+var)
But when I run it
hello("Google")
I am getting NameError.
Please can anybody help me? I am using Windows. Or is it that I have to call by file name and not by function name? If so, how should I call it?
Thanks in advance to whoever helps me.
You need to import your file first:
import myModule
(assuming your file is called myModule.py)
Then you can call the function like this:
myModule.hello('world')
Alternative syntax:
from myModule import hello
hello('world')