urllib.request.Request - unexpected keyword argument 'method' - python

Attempting to use the method argument as seen here yields the following error.
Python 3.2.3 (default, Sep 25 2013, 18:22:43)
>>> import urllib.request as r
>>> r.Request('http://example.com', method='POST')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument 'method'
>>>
No matter what/where I search, I can't seem to find a solution to my problem.

You're looking at the docs for Python 3.3 but running Python 3.2. In Python 3.2 the Request initializer doesn't have a method argument: http://docs.python.org/3.2/library/urllib.request.html#urllib.request.Request
FWIW depending on what kind of request you make (for example if the request includes a body) urllib will automatically use the appropriate method (i.e. POST). If you need to make a more specialized type of request such as HEAD you need to dig a little deeper. There are other answers on SO that help with that.

Related

jupyter is showing callable error in dict function [duplicate]

I was using Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2 , when i ran the folllowing code in it the corresponding error is shown .I searched a lot about this but am unable to find why is it so
>>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
In a fresh interpreter:
>>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
>>> bob
{'age': 42, 'pay': '10000', 'job': 'dev', 'name': 'bob smith'}
However, you are getting a TypeError:
TypeError: 'dict' object is not callable
This error you get tells you that your dict is not callable.
Since my dict is callable when I open a fresh interpreter, it means that your dict is different.
Most likely, you defined a dict variable, which overrode the built-in dict. Look for the
dict = {...}
line, and rename your variable.
As pointed out by #Robᵩ, don't use built-in names for your variables. Especially avoid the tempting str, list, and so on.
On a previous line in that interactive session, you have rebound the dict name to some variable. Perhaps you have a line like dict={1:2} or dict=dict(one=1, two=2).
Here is one such session:
>>> dict=dict(one=1)
>>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
>>>
As a general rule, one should not use built-in type names as variable names, to prevent this error.
edit: Ignore this, I am told this is bad practice.
As mgilson stated, the issue is likely that you have a variable called dict. The solution to this would be to run
del dict
which deletes the variable by that name.

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.

iter() not working with datetime.now()

A simple snippet in Python 3.6.1:
import datetime
j = iter(datetime.datetime.now, None)
next(j)
returns:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
instead of printing out the classic now() behavior with each next().
I've seen similar code working in Python 3.3, am I missing something or has something changed in version 3.6.1?
This is definitely a bug introduced in Python 3.6.0b1. The iter() implementation recently switched to using _PyObject_FastCall() (an optimisation, see issue 27128), and it must be this call that is breaking this.
The same issue arrises with other C classmethod methods backed by Argument Clinic parsing:
>>> from asyncio import Task
>>> Task.all_tasks()
set()
>>> next(iter(Task.all_tasks, None))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
If you need a work-around, wrap the callable in a functools.partial() object:
from functools import partial
j = iter(partial(datetime.datetime.now), None)
I filed issue 30524 -- iter(classmethod, sentinel) broken for Argument Clinic class methods? with the Python project. The fix for this has landed and is part of 3.6.2rc1.
I assume you're using CPython and not another Python implementation. And I can reproduce the issue with CPython 3.6.1 (I don't have PyPy, Jython, IronPython, ... so I can't check these).
The offender in this case is the replacement of PyObject_Call with _PyObject_CallNoArg in the C equivalent of the callable_iterator.__next__ (your object is a callable_iterator) method.
The PyObject_Call does return a new datetime.datetime instance while _PyObject_CallNoArg returns NULL (which is roughly equivalent to an exception in Python).
Digging a bit through the CPython source code:
The _PyObject_CallNoArg is just a macro for _PyObject_FastCall which in turn is a macro for _PyObject_FastCallDict.
This _PyObject_FastCallDict function checks the type of the function (C-function or Python function or something else) and delegates to _PyCFunction_FastCallDict in this case because datetime.now is a C function.
Since datetime.datetime.now has the METH_FASTCALL flag it ends up in the fourth case but there _PyStack_UnpackDict returns NULL and the function is never even called.
I'll stop there and let the Python devs figure out what's wrong in there. #Martijn Pieters already filed a Bug report and they will fix it (I just hope they fix it soonish).
So it's a Bug they introduced in 3.6 and until it's fixed you need to make sure the method isn't a CFunction with the METH_FASTCALL flag. As workaround you can wrap it. Apart from the possibilities #Martijn Pieters mentioned there is also a simple:
def now():
return datetime.datetime.now()
j = iter(now, None)
next(j) # datetime.datetime(2017, 5, 31, 14, 23, 1, 95999)

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

Getting parameter names for __future__ functions in python

My 2.7.5 version of __future__.print_function doesn't allow use of the new argument:
>>> print('hi', end='')
Parsing error SyntaxError: invalid syntax (line 1)
I'll ask about why this is in a separate post if I can't figure that out. For now, I wanted to see what arguments were available in my environment's version of this function.
I looked at this SO post and some related ones, but these do not seem to work when I try:
>>> print.func_code.co_varnames
Parsing error SyntaxError: invalid syntax (line 1)
>>> print_function.func_code.co_varnames
Runtime error
Traceback (most recent call last):
File "<string>", line 1, in <module>
AttributeError: _Feature instance has no attribute 'func_code'
I'm guessing that the special nature of __future__ functions is why this standard technique fails.
Is there another way to check what args my version __future__.print_function takes?
You are trying to treat a built-in function (implemented in C) as a user-defined function. They are not the same thing. .func_code is only defined for user-defined functions (implemented in Python).
The __future__ module only holds metadata about features, the __future__.print_function object is not the same object as the print() function. Instead, the object tells you more about what version of Python first supported the feature, and in what version the feature becomes mandatory (and the from __future__ import becomes a no-op), as well as a bitfield flag for the compile() function:
>>> import __future__
>>> __future__.print_function
_Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 65536)
>>> __future__.print_function.optional
(2, 6, 0, 'alpha', 2)
>>> __future__.print_function.mandatory
(3, 0, 0, 'alpha', 0)
>>> __future__.print_function.compiler_flag
65536
In Python 2.7, built-in function objects such as print() simply do not have enough information for you to discover what arguments they support. In Python 3, this is slowly changing as more and more built-in types are given metadata, but the print() function is not yet among them:
>>> import inspect
>>> inspect.signature(print)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python3.4/inspect.py", line 2045, in signature
return _signature_internal(obj)
File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python3.4/inspect.py", line 1947, in _signature_internal
skip_bound_arg=skip_bound_arg)
File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python3.4/inspect.py", line 1884, in _signature_from_builtin
raise ValueError("no signature found for builtin {!r}".format(func))
ValueError: no signature found for builtin <built-in function print>
I'm not sure where you got the idea from that new is a valid keyword for print() in any Python version however. No version of Python exists that supports that argument.
The only argument that is missing from print() in Python 2 and present in Python 3.3 and up, is the flush argument, see the Python 3 docs for print():
[...] if the flush keyword argument is true, the stream is forcibly flushed.
Changed in version 3.3: Added the flush keyword argument.
The only way to test for that (other than testing with sys.version_info >= (3, 3)) is to try and use it:
from io import StringIO
try:
print('', end='', flush=False, file=StringIO())
print_supports_flush = True
except TypeError:
print_supports_flush = False

Categories

Resources