This question already has answers here:
Bare asterisk in function parameters?
(6 answers)
Closed 4 years ago.
I met a weird case in the function definition in python, I read some code like this:
def abc(dd, *, ee=None):
print(dd, ee)
In the beginning, I thought this code is wrong and maybe a typo of *args, but recently I tried this code in latest python3.7, and it seems that it can be interpreted, and usage is also super wired, you can't pass more than 1 argument to this function:
>>> abc(11, 222)
Traceback (most recent call last):
File "<input>", line 1, in <module>
abc(11, 222)
TypeError: abc() takes 1 positional argument but 2 were given
>>> abc(11)
11 None
I am asking because I don't know the purpose of why some one wrote like this, and why python support this behaviour in Python3(not supported in python2)
It seems your function has 1 positional argument and one named argument. The * eats all other positional arguments, just like an *args would, but you cannot reference them.
Related
This question already has answers here:
How can I specify the function type in my type hints?
(5 answers)
Closed 1 year ago.
So I decided I wanted to make my own custom event system thing and it all works except that on line 2 python is like:
Traceback (most recent call last):
File "d:\CollidaCube\VSCode\GameAPY\event.py", line 1, in <module>
class EventListener():
File "d:\CollidaCube\VSCode\GameAPY\event.py", line 2, in EventListener
def __init__(self, func: function):
NameError: name 'function' is not defined
why is this and how can i fix it? my code
Seon has responded with a valid answer to my question. This has been answered here. In my case, I have decided to use type(abs). its simple and I understand it.
Edit:
After some experimentation I discovered that my VSCode nor python will yell at me if I do type[abs].
This question already has answers here:
Finding the source code for built-in Python functions?
(8 answers)
Closed 1 year ago.
How can I open the underlying script for built-in functions? For example the function len.
I want to open the script of the len function to study how the underlying code is built, for educational purposes.
I have tried writing open(len) and open(len()), but I only get this error message:
Traceback (most recent call last):
File "C:/Users/someo/PycharmProjects/Test/test.py", line 1, in <module>
open(len())
TypeError: len() takes exactly one argument (0 given)
These definitions can't be accessed, because they aren't part of a package. They live in Python itself, therefore they cannot be accessed. You can't get in by making them raise an error either (len(5) won't let you see inside the function, and will just raise a TypeError). Python itself won't show you the full traceback because these definitions aren't meant to be seen.
I'm quite new to Python and I'm studing an opensource framework written in Python. I'm trying to dive a little bit deeper in the source code. I can't understand why the "Arbitrary Arguments" and "Arbitrary Keyword Arguments" are required in this line of code:
observerCallback = lambda *args, **kwargs: self.pushRender(realViewId)
basically because, at the end, they are not used in the "called" method:
def pushRender(self, vId, ignoreAnimation = False):
...
So, once again: what is the purpose of using *args and **kwargs here? I know it could looks like a silly question, but I just learnt right now meaning of this "special operators" and my brain is almost out of work after days spent on exploring this source code. If someone can help me understand a little bit better, for sure I really appreciate that.
The caller of observerCallback is probably passing some arguments to the function, so the function needs to accept them. Otherwise this would happen:
>>> observerCallback = lambda: self.pushRender(realViewId)
>>> observerCallback('foo', bar='baz')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() got an unexpected keyword argument 'bar'
This particular observerCallback simply chooses to ignore/not use any passed arguments. By convention you should use _ instead of "args" and "kwargs" as an indicator that you're going to disregard those arguments:
lambda *_, **__: ...
This question already has answers here:
Can one partially apply the second argument of a function that takes no keyword arguments?
(13 answers)
Closed 5 years ago.
Trying something out with partial, I observed the following behaviour:
First, I defined a function foo which takes 2 non-keyword arguments:
>>> def foo(salutation, name):
... print(salutation, name)
Then, I use partial to create a higher order wrapper.
>>> from functools import partial
>>> f = partial(foo, name='Coldspeed')
Then, called it like this:
>>> f('Hey')
This gave me Hey Coldspeed which was expected. Next, I tried to apply partial to isinstance:
>>> f = partial(isinstance, classinfo=str)
>>> f('hello')
But this gave me an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: isinstance() takes no keyword arguments
I tried classinfo as the argument name since that was what was specified in the docs (linked above). It seems that the actual definition does not have the second argument named classinfo as the docs might otherwise state.
How now, would I create a partial function with the second parameter without being forced to specify the argname? I definitely cannot do f = partial(isinstance, str) because str will be taken as the first argument, not the second. If possible, would like to find a way to do this without using lambda functions too.
Unfortunately, that's just not something functools.partial supports. You'd need to write your own version that does support it, or find one in some 3rd-party library somewhere.
I am working with ceilometer python API and publishing data to pubnub. not sure what is meant by this error.
This is the part of code that is causing the problem i think,
def init_Data(data, channel):
cpu_sample = cclient.samples.list(meter_name ='cpu_util')
for each in cpu_sample:
timetamp = each.timestamp
volume = each.counter_volume
volume_int = int(volume)
data_volume ={'value': volume_int}
data=json.dumps(data_volume)
print (data)
pubnub.publish(channel='orbit_channel', callback= init_Datar)
publish() takes at least 3 arguments (3 given)
Such a terrible error message! One point of confusion is that self is also counted as an argument, even if it's not explicitly provided.
So you need to provide 2 arguments. And you did! But you need to provide the 2 required arguments, while you only provided 1 required and 1 optional argument. Check the API docs for pubnub.publish() to see what you're missing.
While Daniel provided a good explanation, I wanted a minimalist example and was able to come up with this:
>>> class Foo(object):
... def __init__(self, arg1, arg2=None):
... pass
...
>>> Foo(arg2=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes at least 2 arguments (2 given)
So two arguments are provided (self and arg2), but it's saying at least 2 positional arguments are required (self and arg1). So Foo(arg1=1) would work, as would Foo(1, 2) and Foo(1, arg2=2).