Timeout value must be int,Float or None - python-3.x

I was trying setting value of backoff_factor in python code using environment variable.
After that i am trying to call backoff_factor from my crateDB code and it is throwing the following error: ValueError: Timeout value connect was backoff_factor, but it must be an int, float or None.
I wanted the retry interval between retries to connect to database.
Please refer below links for the same:
I am setting export 'backoff_factor'=0.1 here: https://github.com/smartsdk/ngsi-timeseries-api/blob/master/setup_dev_env.sh
Using backoff_factor in crate.py file in my source code using os module: https://github.com/smartsdk/ngsi-timeseries-api/blob/dc565af24b303a94f7c298b2567e62487088de3b/src/translators/crate.py#L64
def setup(self):
environ.get('backoff_factor')
url = "{}:{}".format(self.host, self.port)
self.conn = client.connect([url],'backoff_factor')
self.cursor = self.conn.cursor()
I also tried upgrading urllib3 and request version but not worked out.
Any help will be appreciable.Thanks

The error message seems clear: backoff_factor must be a number or None and you're passing a string:
environment variables are strings, always, you have to convert them to numbers explicitly, Python rarely performs implicit type conversions.
you're not even passing the backoff_factor you defined to connect here, environ.get() returns the value but you're not assigning it, and then you're passing the literal string 'backoff_factor' to connect.
your use of the API also seems odd, I can't find any backoff_factor parameter in the cratedb documentation but given the style if there were one it'd be a keyword parameter (aka client.connect(url, backoff_factor=...))

Related

NamedTuple - сhecking types of fields at runtime

Is there a neat solution to raise an error if a value is passed to the NamedTuple field that does not match the declared type?
In this example, I intentionally passed page_count str instead of int. And the script will work on passing the erroneous value forward.
(I understand that linter will draw your attention to the error, but I encountered this in a case where NamedTuple fields were filled in by a function getting values from config file).
I could check the type of each value with a condition, but it doesn't look really clean. Any ideas? Thanks.
from typing import NamedTuple
class ParserParams(NamedTuple):
api_url: str
page_count: int
timeout: float
parser_params = ParserParams(
api_url='some_url',
page_count='3',
timeout=10.0,
)
By design, Python is a dynamically typed language which means any value can be assigned to any variable. Typing is only supported as hints - the errors might be highlighted in your IDE, but they do not enforce anything.
This means that if you need type checking you have to implement it yourself. On the upside, this can probably be automated, i.e. implemented only once instead of separately for every field. However, NamedTuple does not provide such checking out of the box.

Google ORTools Type Mismatch (Python)

I am attempting to use Google's ORTools in Python to run an optimization. The catch is that the calculations I am trying to optimize have to be accessed through COM, as they are contained in a proprietary piece of external software. Is there any way to accomplish this?
The COM Object accepts integer or float values as inputs, but ORTools passes variables as variable objects, so the COM object is unable to use them. I attempted to get around this by using the solution_value() method, as this was the only method I could find to access variable values, but this issues the following error message and causes the solver to stop working:
"The model has been changed since the solution was last computed. MPSolverInterface:: sync_status_ = 0".
If I just pass the variable to the COM Object, I get the following error:
"Exception has occurred: TypeError. must be real number, not Variable."
See below for my example code:
from ortools.linear_solver import pywraplp
import win32com.client as win32
Program = win32.Dispatch("CalcProgram")
def Calculations(x,y):
Program.SetValue(x)
Program.SetValue(y.solution_value())
return Program.GetValue(Z)
solver = pywraplp.Solver.CreateSolver('SCIP')
x = solver.IntVar(1,25)
y = solver.IntVar(30,60)
solver.Minimize(Calculations(x,y))
status = solver.Solve()
You are missing the point of the linear solver and how to use it.
solver.Minimize() takes a linear expression, that is a python object built with overloaded +, -, * operators and variables and constants.
a valid call could be:
solver.Minimize(x + 2 * y)
Furthermore, solution_value() can only called after a successful Solve().
You should look at python samples to see how programs are structured.
See https://github.com/google/or-tools/blob/stable/ortools/linear_solver/samples/simple_mip_program.py

python function parameter:complex parameter structure understanding

def resize_img( size: Tuple[int, int] = (299, 299)):
pass
What does the parameter mean?I did not find the docs.
In case you are asking about Tuple[int, int]: this syntax is provided by typing module. It helps you and other people reading your code to understand which type should parameters have when passed into function. In your example - if you try to pass something different than tuple of two ints (i.e. resize_img(5)) IDE will mark it as Expected type 'Tuple[int]', got 'int' instead. This does not break code execution, but shows developer that probably he/she uses this function with wrong type of parameter passed in.

Mypy falsely reports error on union-typed variable when branching on type

I ran into an issue when using mypy and have been able to find any help/reports regarding it. The following simplified code and error message should be self-explanatory:
#!/usr/bin/env python3
from typing import List, Union
class Corpus:
path: List[str]
def __init__(self, path:Union[str,List[str]]) -> None:
if type(path) == str:
self.path = [path]
else:
self.path = path
Mypy gives the following errors:
simplified.py:10: error: List item 0 has incompatible type "Union[str, List[str]]"; expected "str"
simplified.py:12: error: Incompatible types in assignment (expression has type "Union[str, List[str]]", variable has type "List[str]")
Even though the type of path variable is checked so that self.path should always result in string list, mypy complains about incompatible types.
Am I overlooking something or is this a bug in mypy?
(It it is a bug, should I go with #type: ignore annotation or is there a better work-around?)
(Some background: I decided to ease my life by writing a module which would take care of some repeating work. The argument in question should be a path to text data and I expect it to be only one string most of the time so I don't want to force putting it in a list. However, I wish to allow specifying more paths too. Internally, I store it as a list anyway as iterator over the class is always initialized with such list (and then possibly extends it further by "unpacking" directories)).
Try using isinstance(path, str) instead of type(path) == str. The former makes mypy typecheck your code without reporting an error.
Mypy really ought to support the latter form though -- there's an open feature request about it. The reason why this isn't implemented yet is almost certainly due to lack of time -- mypy's core team is pretty small, and there's an easy workaround in this case, so the feature was deprioritized.
(But hey, mypy is open source, so if you have some spare time...)

How to print __init__ function arguments in python?

I am trying to create a dictionary of class names residing in module to their constructor args.
Constructor args should also be a dictionary where I will store the default values of the arguments wherever defined.
Any leads will be really helpful. Thanks in advance.
To provide more details about the use case, What I am trying to do here is for all the classes mentioned in the image image
I want to get the constructor parameters for e.g. please refer below image
image
If I understand you correctly, you just want the name of the parameters in the signature of your __init__.
That is actually quite simple using the inspect module:
Modern python answer:
import inspect
signature = inspect.signature(your_class.__init__).parameters
for name, parameter in signature.items():
print(name, parameter.default, parameter.annotation, parameter.kind)
Outdated answer
import inspect
signature = inspect.getargspec(your_class.__init__)
signature.args # All arguments explicitly named in the __init__ function
signature.defaults # Tuple containing all default arguments
signature.varargs # Name of the parameter that can take *args (or None)
signature.keywords # Name of the parameter that can take **kwargs (or None)
You can map the default arguments to the corresponding argument names like this:
argument_defaults = zip(signature.args[::-1], signature.defaults[::-1])
Most recently, the following works:
import inspect
signature = inspect.signature(yourclass.__init__)
for param in signature.parameters.values():
print(param)
The difference being (compared to the accepted answer), that the parameters instance variable needs to be accessed.

Resources