inspect.getsource() doesn't work in python - python

I have a problem with this code , but don't no why...
import inspect
inspect.getsource(min)
and the error is:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
inspect.getsource(min)
File "C:\Python33\lib\inspect.py", line 726, in getsource
lines, lnum = getsourcelines(object)
File "C:\Python33\lib\inspect.py", line 715, in getsourcelines
lines, lnum = findsource(object)
File "C:\Python33\lib\inspect.py", line 551, in findsource
file = getfile(object)
File "C:\Python33\lib\inspect.py", line 435, in getfile
'function, traceback, frame, or code object'.format(object))
TypeError: <built-in function min> is not a module, class, method, function, traceback, frame,or code object

The built-in min() is implemented in C code, and inspect.getsource() can only show you Python code:
>>> min
<built-in function min>
The built-in function type is always implemented in C.
The code for this function comes from the bltinmodule.c source file; the builtin_min() function delegates to the min_max() utility function in the same source file.

Related

Getting weird error on running python in cmd then continue normally

When I run python on cmd I get this weird error:
Failed calling sys.__interactivehook__
Traceback (most recent call last):
File "C:\Users\Khaled\AppData\Local\Programs\Python\Python310\lib\site.py", line 446, in register_readline
import readline
File "C:\Users\Khaled\AppData\Local\Programs\Python\Python310\lib\site-packages\readline.py", line 34, in <module>
rl = Readline()
File "C:\Users\Khaled\AppData\Local\Programs\Python\Python310\lib\site-packages\pyreadline\rlmain.py", line 422, in __init__
BaseReadline.__init__(self)
File "C:\Users\Khaled\AppData\Local\Programs\Python\Python310\lib\site-packages\pyreadline\rlmain.py", line 62, in __init__
mode.init_editing_mode(None)
File "C:\Users\Khaled\AppData\Local\Programs\Python\Python310\lib\site-packages\pyreadline\modes\emacs.py", line 633, in init_editing_mode
self._bind_key('space', self.self_insert)
File "C:\Users\Khaled\AppData\Local\Programs\Python\Python310\lib\site-packages\pyreadline\modes\basemode.py", line 162, in _bind_key
if not callable(func):
File "C:\Users\Khaled\AppData\Local\Programs\Python\Python310\lib\site-packages\pyreadline\py3k_compat.py", line 8, in callable
return isinstance(x, collections.Callable)
AttributeError: module 'collections' has no attribute 'Callable'
But then I continue using python normally:
>>>
I did not find any effects of this problem python is running normally but I do not want it to appear and to know what does it do.

How can I use CUDA with vaex (a Python library)

my code as follow:
df['O_ID'] = (df.apply(get_match_id, arguments=[df['pickup_longitude'], df['pickup_latitude']])).jit_cuda()
When first I used this function——jit_cuda(),there was an error "No Module named cupy"
But, when I have installed the cupy-cuda101(Adapt to my CUDA version)
I get a new error
Traceback (most recent call last):
File "F:\Anaconda3\lib\site-packages\vaex\dataframe.py", line 3580, in table_part
values[name] = df.evaluate(name)
File "F:\Anaconda3\lib\site-packages\vaex\dataframe.py", line 2616, in evaluate
return self._evaluate_implementation(expression, i1=i1, i2=i2, out=out, selection=selection, filtered=filtered, internal=internal, parallel=parallel, chunk_size=chunk_size)
File "F:\Anaconda3\lib\site-packages\vaex\dataframe.py", line 5352, in _evaluate_implementation
dtypes[expression] = df.data_type(expression, internal=False)
File "F:\Anaconda3\lib\site-packages\vaex\dataframe.py", line 1998, in data_type
data = self.evaluate(expression, 0, 1, filtered=True, internal=True, parallel=False)
File "F:\Anaconda3\lib\site-packages\vaex\dataframe.py", line 2616, in evaluate
return self._evaluate_implementation(expression, i1=i1, i2=i2, out=out, selection=selection, filtered=filtered, internal=internal, parallel=parallel, chunk_size=chunk_size)
File "F:\Anaconda3\lib\site-packages\vaex\dataframe.py", line 5427, in _evaluate_implementation
value = scope.evaluate(expression)
File "F:\Anaconda3\lib\site-packages\vaex\scopes.py", line 97, in evaluate
result = self[expression]
File "F:\Anaconda3\lib\site-packages\vaex\scopes.py", line 139, in __getitem__
self.values[variable] = self.evaluate(expression) # , out=self.buffers[variable])
File "F:\Anaconda3\lib\site-packages\vaex\scopes.py", line 103, in evaluate
result = eval(expression, expression_namespace, self)
File "<string>", line 1, in <module>
File "F:\Anaconda3\lib\site-packages\vaex\expression.py", line 1073, in __call__
return self.f(*args, **kwargs)
File "F:\Anaconda3\lib\site-packages\vaex\expression.py", line 1120, in wrapper
return cupy.asnumpy(func(*args))
File "cupy\core\fusion.pyx", line 905, in cupy.core.fusion.Fusion.__call__
File "cupy\core\fusion.pyx", line 754, in cupy.core.fusion._FusionHistory.get_fusion
File "<string>", line 6, in f
NameError: name 'lambda_function_1' is not defined
How should I solve it?
My understanding is that just-in-time compilation in vaex works only for virtual columns, or expressions/columns computed mainly with various arithmetic operations using numpy methods or pure python arithmetics.
When using apply, a function can be quite abstract, basically whatever you want, so it may not be possible for it to be compiled.
If you can rewrite your .apply function using numpy expressions, then you are likely able to use the jit_cuda method to accelerate it. Vaex does not recommend using .apply anyway, since it is hard to parallelize and should be used a "last resort" of sorts.
Source: https://vaex.io/docs/tutorial.html#Just-In-Time-compilation

Generic function typing in Python

I am running under Python 3.7 on Linux Ubuntu 18.04 under Eclipse 4.8 and Pydev.
The declaration:
args:Dict[str: Optional[Any]] = {}
is in a module that is imported from my testing code. and it is flagged with the following error message from typing.py:
TypeError: Parameters to generic types must be types. Got slice(<class 'str'>, typing.Union[typing.Any, NoneType], None). The stack trace follows: Finding files... done. Importing test modules ... Traceback (most recent call last): File "/Data/WiseOldBird/Eclipse/pool/plugins/org.python.pydev.core_7.0.3.201811082356/pysrc/_pydev_runfiles/pydev_runfiles.py", line 468, in __get_module_from_str
mod = __import__(modname) File "/Data/WiseOldBird/Workspaces/WikimediaAccess/WikimediaLoader/Tests/wiseoldbird/loaders/TestWikimediaLoader.py", line 10, in <module>
from wiseoldbird.application_controller import main File "/Data/WiseOldBird/Workspaces/WikimediaAccess/WikimediaLoader/src/wiseoldbird/application_controller.py", line 36, in <module>
args:Dict[str: Optional[Any]] = {} File "/usr/local/lib/python3.7/typing.py", line 251, in inner
return func(*args, **kwds) File "/usr/local/lib/python3.7/typing.py", line 626, in __getitem__
params = tuple(_type_check(p, msg) for p in params) File "/usr/local/lib/python3.7/typing.py", line 626, in <genexpr>
params = tuple(_type_check(p, msg) for p in params) File "/usr/local/lib/python3.7/typing.py", line 139, in _type_check
raise TypeError(f"{msg} Got {arg!r:.100}.") TypeError: Parameters
This prevents my testing module from being imported.
What am I doing wrong?
The proper syntax for a dict's type is
Dict[str, Optional[Any]]
When you write [a: b], Python interprets this as a slice, i.e. the thing that makes taking parts of arrays work, like a[1:10]. You can see this in the error message: Got slice(<class 'str'>, typing.Union[typing.Any, NoneType], None).

Why can't I use inspect.getsource() to view the source for list?

I tried to retrieve the source code for the list class using the inspect module, without success:
>>> import inspect
>>> inspect.getsource(list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "/usr/lib/python2.7/inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "/usr/lib/python2.7/inspect.py", line 526, in findsource
file = getfile(object)
File "/usr/lib/python2.7/inspect.py", line 408, in getfile
raise TypeError('{!r} is a built-in class'.format(object))
TypeError: <module '__builtin__' (built-in)> is a built-in class
I don't understand why this didn't work - the documentation for inspect.getsource() says that
An IOError is raised if the source code cannot be retrieved.
... but doesn't explain why that might happen (and in any case I got a TypeError, not an IOError).
Is there some other way I can programmatically retrieve the source for an object in cases like this? If not, how can I find the source for myself?
While inspect.getsource() can retrieve the source code for objects written in Python, list is written in C, so there's no Python source for getsource() to retrieve.
If you're comfortable reading C, you can find the complete source code for Python at its official GitHub repo. For example, the source of list for various releases can be found at:
https://github.com/python/cpython/blob/master/Objects/listobject.c (latest development version)
https://github.com/python/cpython/blob/3.6/Objects/listobject.c
https://github.com/python/cpython/blob/2.7/Objects/listobject.c
... and so on.

Missing python 3 API functions

I was coding something at work and it seems that some C API functions provided by python are not working. I tried mainly the function that check types, for example:
import ctypes
python33_dll = ctypes.CDLL('python33.dll')
a_float = python33_dll.PyFloat_FromDouble(ctypes.c_float(2.0))
python33_dll.PyFloat_Check(a_float)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
python33_dll.PyFloat_Check(a_float)
File "C:\Python33\lib\ctypes\__init__.py", line 366, in __getattr__
func = self.__getitem__(name)
File "C:\Python33\lib\ctypes\__init__.py", line 371, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'PyFloat_Check' not found
Is there anything specific I need to do to use this function, or is it a bug?
docs.python.org/3.3/c-api/float.html?highlight=double#PyFloat_Check
PyFloat_Check() is a macro. You will need to expand it manually and call the correct function instead.

Categories

Resources