Calling Method with and without Parentheses in Python [duplicate] - python

This question already has answers here:
What does it mean when the parentheses are omitted from a function or method call?
(6 answers)
Closed 2 years ago.
I've realized that some methods should be called with (), while others can't. How can I check, using IPython e.g., whether to use parentheses or not? For example the following file scratch.py
import numpy as np
arr = np.random.randn(5)
print arr.sort, "\n"
print arr.sort(), "\n";
print arr.shape, "\n";
print arr.shape(), "\n";
produces this output:
<built-in method sort of numpy.ndarray object at 0x7fb4b5312300>
None
(5,)
Traceback (most recent call last):
File "scratch.py", line 8, in <module>
print arr.shape(), "\n";
TypeError: 'tuple' object is not callable

Those are not methods, those are properties. The descriptor is invoked behind the scenes by Python itself.

Methods in Python are always invoked with a ().
Best way to check if something is a method is to read the documentation of the library.

Related

Problems about python ctypes module

Just trying to mess around and learn about python ctypes according to the official documentation at https://docs.python.org/3.8/library/ctypes.html
Everything works just fine until:
ValueError is raised when you call an stdcall function with the cdecl calling convention, or vice versa:
>>> cdll.kernel32.GetModuleHandleA(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>
>>> windll.msvcrt.printf(b"spam")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
quoted from official documentaion, while i get is:
>>> cdll.kernel32.GetModuleHandleA(None)
1374486528
>>> windll.msvcrt.printf(b"spam")
4
according to those MS documentation, seems these function calls work just fine
What's more, I also tried to mess around with the argument number so as to raise a ValueError, but that's what I get:
>>> cdll.kernel32.GetModuleHandleA(None,0,0)
1374486528
>>> windll.kernel32.GetModuleHandleA(0,0,0)
1374486528
>>> windll.kernel32.GetModuleHandleA()
0
>>> cdll.kernel32.GetModuleHandleA()
0
Seems the last two function calls does return null as there was an error, but no Value error exception.
The only error i got is OSError, just as the documentation example shows.
Can anyone explain this? I create virtual environment using conda and I test these codes both in python 3.6.12 and python 3.8.5.
And by the way ,according to the documentation: "ValueError is raised when you call an stdcall function with the cdecl calling convention, or vice versa", I wonder what exactly "call an stdcall function with cdecl calling convention" means? Maybe just by giving different number of arguments rather than the function required?
__stdcall and _cdecl have no difference on 64-bit compilers. There is only one calling convention and the notations are ignored and both WinDLL and CDLL work. 32-bit code is where it matters and the correct one must be used.
You should still use the appropriate WinDLL or CDLL in scripts if you want the script to work correctly on both 32-bit and 64-bit Python.

Why executing a function from another program that creates a new object then accessing it returns an error [duplicate]

This question already has answers here:
Setting variables with exec inside a function
(2 answers)
Cannot change global variables in a function through an exec() statement?
(3 answers)
Closed 4 years ago.
I am trying to create a function that will create a new object of a class through exec every time called, but I could not access the object.
Here is a piece of example code:
a.py:
class test(object):
def __init__(self):
self.var='vari'
def testfunc():
exec("""aaa=test()
aaa.var='varia'""")
b.py:
import a
a.testfunc()
print(a.aaa.var)
When running b.py, it returns the following:
Traceback (most recent call last):
File "C:\Users\lenovo\Desktop\pythontest\b.py", line 3, in
print(a.aaa.var)
AttributeError: module 'a' has no attribute 'aaa'
Why is this?
I looked at Take_Care_'s comment, then tested it out. If I globalize aaa before assigning it to an object of test, I could access it from b.py.

What is the type of print in Python? [duplicate]

This question already has answers here:
What is 'print' in Python?
(5 answers)
Closed 7 years ago.
sum is a builtin function in Python, so that's why I get this output.
>>> type(sum)
<type 'builtin_function_or_method'>
But when I do,
>>> type(print)
It returns
File "<stdin>", line 1
type(print)
^
SyntaxError: invalid syntax
So, is there no type of print? Is print an exception to the type() function?
I am using Python 2.7
In Python 2, print is a statement, which is a whole different kind of thing from a variable or function. Statements are not Python objects that can be passed to type(); they're just part of the language itself, even more so than built-in functions. For example, you could do sum = 5 (even though you shouldn't), but you can't do print = 5 or if = 7 because print and if are statements.
In Python 3, the print statement was replaced with the print() function. So if you do type(print), it'll return <class 'builtin_function_or_method'>.
BONUS:
In Python 2.6+, you can put from __future__ import print_function at the top of your script (as the first line of code), and the print statement will be replaced with the print() function.
>>> # Python 2
>>> from __future__ import print_function
>>> type(print)
<type 'builtin_function_or_method'>
print is not a function in Python 2, it is a statement.

Benefits on #staticmethod in python3? [duplicate]

This question already has answers here:
Are there any benefits from using a #staticmethod?
(4 answers)
Closed 7 years ago.
I have a simple question : why using the staticmethod decorator on static methods ? You can make static methods that don't have the "self" parameter, without this decorator.
When using python2, it was necessary :
>>> class A:
... def p(object_to_print):
... print(object_to_print)
...
>>> A.p('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method p() must be called with A instance as first argument (got str instance instead)
However, if I do the exact same thing using python 3, it will works fine.
Why using a decorator if it works fine without it ? If the first parameter is not named self, it is quite obvious it is a static method. The only reason I can see is to get clearer error in cases of misuseā€¦
Is there any reason for this behaviour in python 3 ?
Thanks :)
palkeo.
Try to call this method with an instance of A and you'll get an exception:
>>> a = A()
>>> a.p('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: p() takes 1 positional argument but 2 were given
Because the argument is considered as the instance itself:
>>> a.p()
<__main__.A object at 0x7f9f60f56048>
However, if the method is decorated with staticmethod, it works as expected:
>>> A.p('test')
test
>>> a.p('test')
test

Add __getitem__ to module [duplicate]

This question already has an answer here:
Python: subscript a module
(1 answer)
Closed 7 years ago.
So it's quite a simple question. how do I add __getitem__ to a Python module. I mostly just want it as an ease of use, however it's confusing why it wouldn't let me 'just set it'. Below is a simple example of __getitem__ semi-working, however I wish for the other['test'] to work.
Here's the full output:
hello
hello
Traceback (most recent call last):
File "main.py", line 4, in <module>
print other['test']
TypeError: 'module' object has no attribute '__getitem__'
main.py
import other
print other.get('test')
print other.__getitem__('test')
print other['test']
other.py
test = 'hello'
def __getitem__(name):
return globals()[name]
get = __getitem__
I've tried to set __getitem__ using globals() aswell, globals()['__getitem__'] = __getitem__. It didn't work. And I tried to set it in main.py. So I'm confused as to why it's so adamant in not allowing me to use other['test'].
If it's impossible, then a short reason would be good.
Special methods are looked up on the type, not on an instance. Python looks for type(other).__getitem__() and that isn't available. You'd have to add the __getitem__ method to the module type; you can't in Python.
You'd have to replace the whole module instance in sys.modules with an instance of your own class to achieve what you want:
class MyModule(object):
def __init__(self, namespace):
self.__dict__.update(namespace)
def __getitem__(name):
return self.__dict__[name]
import other
import sys
sys.modules[other.__name__] = MyModule(other.__dict__)
This limitation doesn't just apply for modules, it applies for anything such that the type is not object or some subclass of object, or something with a metaclass that never bottoms out with object in the mro.
For example, you can also see this happening with type type:
In [32]: class Foo(type):
....: pass
....:
In [33]: type(Foo)
Out[33]: type
In [34]: Foo.__getitem__ = lambda x, y: x.__dict__.get(y)
In [35]: Foo.foo = "hello"
In [36]: Foo['foo']
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-e354ca231ddc> in <module>()
----> 1 Foo['foo']
TypeError: 'type' object has no attribute '__getitem__'
In [37]: Foo.__dict__.get('foo')
Out[37]: 'hello'
The reason is that at the C-API level, both module and type are particular instances of PyTypeObject which don't implement the required protocol for inducing the same search mechanism that the PyTypeObject implementation of object and friends does implement.
To change this aspect of the language itself, rather than hacking a replacement of sys.modules, you would need to change the C source definitions for PyModule_Type and PyType_Type such that there were C functions created for __getitem__ and added to the appropriate location in the C-API big PyTypeObject struct-o-magic-functions (a lot of which is expanded by the macro PyObject_HEAD) instead of 0 (which is the sentinel for does not exist), and recompile Python itself with these modified implementations of module and type.

Categories

Resources