mypy Error: Unexpected keyword argument for "__init_subclass__" of "object" - subclass

I'm facing this error in mypy for an __init__subclass
main.py:7: error: Unexpected keyword argument "swallow" for "__init_subclass__" of "object" [call-arg] /layers/google.python.pip/pip/lib/python3.10/site-packages/mypy/typeshed/stdlib/builtins.pyi:113: note: "__init_subclass__" of "object" defined here Found 1 error in 1 file (checked 1 source file)
here is mypy playground sample code :
(https://mypy-play.net/?mypy=latest&python=3.10&gist=010f4102ed9a2ff8fd53fc69c76c14f8)
It's raised on a huge existing code base and is very hard to use #type: ignore. any possible explanation of this error would be really helpful , Thanks
sample code to reproduce this error on mypy playground:
class Base:
def __init__subclass(cls, swallow, **kwargs):
super().__init_subclass__(**kwargs)
class Child(Base, swallow="african"):
def __init__(self) -> None:
super(Child, self).__init__()

Related

Unexpected index error using choice module

I've been trying to use args in a function so that it can accept an unspecified amount of parameters but during testing I seem to be lumped with this error. Which seems to be produced by the choice module itself not the file i'm writing.
File "C:\ProgramFiles\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\random.py", line 378, in choice
return seq[self._randbelow(len(seq))]
IndexError: list index out of range
Here is the code i'm trying to run:
def key_word_choice(key, *otherkeys):
key_choice = []
for items in sauces:
if key and otherkeys in items:
key_choice.append(items[0])
print("You should choose:", choice(key_choice))
key_word_choice('hot', 'garlic', 'buffalo')

How to create and fill structured array with numba?

Python 3.9.7, Numba 0.54.0
I wrote this simple code, that works well:
import numpy as np
import numba
from collections import namedtuple
Deal = namedtuple('Deal' , ['DateTime', 'Price', 'Quantity'])
dtype_deals = [('DateTime', 'datetime64[s]'), ('Price', 'float64'), ('Quantity', 'uint64')]
# #numba.njit
def my_func():
deals = []
deals.append(Deal(np.datetime64('2015-02-27T15:12:12'), 12.48, 10))
deals.append(Deal(np.datetime64('2015-03-17T15:08:36'), 1.15, 100))
deals.append(Deal(np.datetime64('2015-04-02T15:14:32'), 11.01, 20))
return np.array(deals, dtype=dtype_deals)
print(str(my_func()))
But when I remove the comment before #numba.njit, I get a mistake:
numba.core.errors.TypingError: Failed in nopython mode pipeline (step:
nopython frontend) No implementation of function
Function(datetime64[]) found for signature:
(Literalstr) There are 2 candidate implementations:
Of which 1 did not match due to: Overload in function 'make_callable_template..generic': File:
numba/core/typing/templates.py: Line 174. With argument(s):
'(unicode_type)': Rejected as the implementation raised a specific
error:
TypingError: Casting unicode_type to datetime64[] directly is unsupported. raised from
/home/ivan/.local/lib/python3.9/site-packages/numba/core/typing/builtins.py:818
Of which 1 did not match due to: Overload in function 'make_callable_template..generic': File:
numba/core/typing/templates.py: Line 174. With argument(s):
'(Literalstr)': Rejected as the
implementation raised a specific error:
TypingError: Casting Literalstr to datetime64[] directly is unsupported. raised from
/home/ivan/.local/lib/python3.9/site-packages/numba/core/typing/builtins.py:818
During: resolving callee type: class(datetime64[])
During: typing of call at /home/ivan/eclipse-workspace/MarketAnalysis/Experiment.py (11)
File "Experiment.py", line 11: def my_func():
deals = []
deals.append(Deal(np.datetime64('2015-02-27T15:12:12'), 12.48, 10))
^

How to raise timeout error in unittesting

This is first time i am touching ruby, so no sure about correct terminology. I have tried searching for mulitple things, but couldn't find a solution.
I have this code block
domain_response = MyDomain::Api::MyApi::Api.new(parameters: message.to_domain_object, timeout: 1000)
# :nocov:
case (response = domain_response.response)
when MyDomain::Api::MyApi::SuccessResponse
## do something
when Domain::ErrorResponses::TimeoutResponse
## do something.
now i am trying to testing TimeoutResponse, I have written(tried) this
it "when api call timesout" do
expect(MyDomain::Api::MyApi::Api).to{
receive(:new)
} raise_error(MyDomain::ErrorResponses::TimeoutResponse)
end
this gave me error that unexpected identifier.
I have also tried by not providing receive, and it gave me error that block is expected.
Whats the proper way to raise an error that i can test?
Update:
Here is where i am stuck now
it "when api call timesout" do
# 1
expect(MyDomain::Api::MyApi::Api).to(
receive(:new),
).and_return(domain_api_instance)
# 2
expect(domain_api_instance.response).to receive(:response).and_raise(Domain::ErrorResponses::TimeoutResponse)
expect(domain_api_instance.response).to eq(ApiError::Timeout)
end
But with this code i am getting this error
1) Rpc::Package::SubPackage::V1::PackageService#first_test testing when api call timesout
Failure/Error: expect(domain_api_instance.response).to receive(:response).and_raise(Domain::ErrorResponses::TimeoutResponse)
#<InstanceDouble(MyDomain::Api::MyApi::Api) (anonymous)> received unexpected message :response with (no args)

How to print Graphene-Django / Graphene-Python Exceptions to the Console for Debugging?

When a GraphQL Error occurs, I cannot easily know where it occured. I have to spend unnecessary time trying to track it down. How do I get a Traceback printed in the console of my text editor?
I answered my own question by accessing the GraphQL error(s) with result.errors, iterating through the list, and using python's print_tb function to print the Traceback.
Does anyone have a different or better way of doing it?
Example usage of the print_graphql_errors function:
from django.conf.settings import DEBUG
result = schema.execute(
mutation_str, context_value=request, variable_values=variable_values
)
if result.errors is None:
return self.handle_success(result)
if DEBUG:
print_graphql_errors(result.errors)
return self.handle_failure(result)
The print_graphql_errors function:
from traceback import print_tb
from django.conf.settings import DEBUG
def print_graphql_errors(errors, raise_error=False):
if not DEBUG:
raise Exception(
'DevError: This function should not be called in production'
)
assert errors, 'DevError: The "errors" parameter cannot be None'
print_after = []
current_error = None
print('######################################################################')
print('Manually Generated Traceback (with the print_graphql_errors function):')
print(f'There are {len(errors)} errors:')
for i, error in enumerate(errors):
print(f'{i + 1}) ', error)
print('######################################################################')
for error in errors:
current_error = error
# FYI: This object has these attributes: (example attribute values)
# tb_frame <frame at 0x000002DDB844D548, file 'site-packages\\graphql\\execution\\executor.py', line 455, code resolve_or_error>
# tb_lasti 16
# tb_lineno 447
# tb_next <traceback object at 0x000002DDBAFBA388>
# print('error.locations:', error.locations)
# print('error.positions:', error.positions)
try:
print_tb(error.stack)
except AttributeError as e:
print(e.__traceback__)
print(f'Warning: An error occured while trying to print the traceback: {e}. It has the following attributes instead: {dir(error)}')
print_after.append(error)
if len(print_after):
print('###################################################################')
print(f'Number of errors without the "stack" attribute: {len(print_after)}')
print('###################################################################')
if raise_error:
for error in print_after:
raise error
raise current_error

Getting a WARNING and ERROR: unexpected keyword argument 'queryset'

Unexpected keyword argument 'queryset' in constructor call [E:unexpected-keyword-arg]
Tried using form_kwargs as shown on stack overflow here:
# How to use the new form_kwargs on an inline formset?
if request.method == "POST":
ctx['formset'] = project_comparison_form_set(
data=request.POST, files=request.FILES, queryset=ctx['projects'])
ctx['data1'] = request.POST.copy
if ctx['formset'].is_valid():
instances = ctx['formset'].save(commit=False)
for project in instances:
project.save()
Getting both a warning and error message in pylint Unexpected keyword argument 'queryset' in constructor call [E:unexpected-keyword-arg]
You don't show where project_comparison_form_set is defined, but i assume that it is a modelformset_factory.
Here, you do not have the queryset argument. If you do want to pass a queryset, you can pass it to the formset and the formset than to the modelformset_factory.
Check the documentation https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#changing-the-queryset.

Resources