How to fix this IndetationError in python? - python-3.x

from timeit import Timer
timer_obj1 = Timer('list_sum()'),
'from_main_import list_sum'
timer_obj2 = Timer('numpy_arr_sum()'),
'from_main_import numpy_arr_sum'
print('Pure python version:',timer_obj1.timeit(1000))
print('Numpy version:',timer_obj2.timeit(1000))
this is the code I key in
after run it, shows unexpected indent in line 3
Anyone can help me out, please?

You closed the parentheses of Timer class's constructor (basically a function), but attempted to insert another argument to it with a different indent. You can't do that.
Do it like that:
from timeit import Timer
timer_obj1 = Timer('list_sum()',
'from_main_import list_sum')
timer_obj2 = Timer('numpy_arr_sum()',
'from_main_import numpy_arr_sum')
...

Related

Is there correct way to use python typing?

I'm trying to figure out typing in Python and I'm having trouble with the following code:
from collections.abc import Iterable
from typing import TypeVar
T = TypeVar('T')
def convert_to_iter(var: T | Iterable[T]) -> Iterable[T]:
if not isinstance(var, Iterable):
return (var, )
return var
I am using Pylance in VScode with typeCheckingMode: "strict" and am getting the error on the last line of the code:
Return type, "Iterable[Unknown]* | Iterable[T#convert_to_list]", is partially unknown Pylance(reportUnknownVariableType)
Can someone please explain why this is incorrect?
There is a discussion in this issue about such question.
So, this behavior can be explained by type narrowing.
One of the existing ways to eliminate this error is to use cast function

Using suppressMessages in rpy2 still prints messages

I'd like to suppress messages from R in rpy2 and thought the following would be enough:
>>> from rpy2.robjects.packages import importr
>>> import rpy2.robjects as robjs
>>> suppmsg = robjs.r["suppressMessages"]
but then I get:
>>> suppmsg(robjs.r.message("hello"))
R[write to console]: hello
I don't mind the messages during interactive work, but I want them off in a library. How can they be turned off?
Your code might not do what you expect to because in R the evaluation of expressions is lazy and in Python it is not.
For example, when doing in R
suppressMessages(library("foo"))
what happens is that the function suppressMessages() is called with the unevaluated expression library("foo") as an argument. In the body of the function suppressMessages() code that turns off the display of messages globally is first run, and then the expression is evaluated, and finally code that restores the display of messages is run.
In Python, doing
suppmsg(robjs.r.message("hello"))
will first evaluate robjs.r.message("hello") (which calls the R function function message() through rpy2) and the result of this evaluation (what is returned by the function) is passed as an argument to suppmsg().
If you only want to silence import of a library, the function rpy2.robjects.packages.quiet_require() can do that for you.

How to replace the call to random.randint() in a function tested with pytest?

I'm new to programming and did search a lot through the questions but couldn't find an answer to my present problem.
I am writing a little game in python 3.8 and use pytest to run some basic tests.
One of my tests is about a function using random.randint()
Here's an extract of my code :
import random
...
def hit(self, enemy, attack):
dmg = random.randint(self.weapon.damage_min, self.weapon.damage_max) + self.strength // 4
hit() does other things after that but the problem is with this first line.
I tried to use monkeypatching to get a fake random number for the test :
def test_player_hit_missed(monkeypatch, monster, hero):
monkeypatch.setattr('random.randint', -3)
hero.hit(monster, 'Scream')
assert monster.life == 55
When I run the test, I get this error :
TypeError: 'int' object is not callable
From what I understand, the monkey-patch did replace randint() by the number I indicated (-3), but then my function hit() did try to call it nonetheless.
I thought -3 would replace randint()'s result.
Can someone explain me :
- why this doesn't work (I probably haven't correctly understood the behavior of the monkeypatch) ?
- and how I can replace the call to random.randint() by the value -3 during the test ?
Thanks

Python object exceeds recursion depth

I'm writing this program to process some lab results for college written in a .txt file. However, when I launch the program,it says there's a recursion error and the python object exceeds recursion depth. How can I solve this?
from math import *
from numpy import *
D=0.946
iD=0.001
diametros=loadtxt("bolas.txt",delimiter=",")
ind=loadtxt("incertezas.txt",delimiter=",")
for d in diametros :
for incertd in ind:
a=1+(9*d/(4*D))+(9*d/(4*D))**2
def incerteza(D,d,incertd,iD):
incert= sqrt((((9/(4*D))+(9*d/(2*D**2))*incertd)**2+(((-9*d/(4*D**2))+(-9*d/(2*D**3)))*iD)**2))
return incerteza(D,d,incertd,iD);
j=incerteza(D,d,incertd,iD)
r.append(a)
i.append(j)
print (r,i)
The culprit is in here:
def incerteza(D,d,incertd,iD):
incert= sqrt((((9/(4*D))+(9*d/(2*D**2))*incertd)**2+(((-9*d/(4*D**2))+(-9*d/(2*D**3)))*iD)**2))
return incerteza(D,d,incertd,iD);
The function incerteza keeps calling itself, with the exact same parameters, over and over and over again.
Maybe you meant to return incert ?

Call a function dynamically from a variable - Python

Ok so I have two files, filename1.py and filename2.py and they both have a function with same name funB. The third file process.py has function that calls function from either files. I seem to be struggling in calling the correct function.
In process.py:
from directoryA.filename1 import funB
from directoryA.filename2 import funB
def funA:
#do stuff to determine which filename and save it in variable named 'd'
d = 'filename2'
# here i want to call funB with *args based on what 'd' is
So i have tried eval() like so:
call_right_funB = eval(d.funB(*args))
but it seems not to work.
Any help is appreciated.
The problem is, you can't use eval() with a combination of a string and a method like that. What you have written is:
call_right_funB = eval('filename'.funB(*args))
What you can do is:
call_right_funB = eval(d + '.funB(*args)')
But this is not very pythonic approach.
I would recommend creating a dictionary switch. Even though you have to import entire module:
import directoryA.filename1
import directoryA.filename2
dic_switch = {1: directoryA.filename1, 2: directoryA.filename2}
switch_variable = 1
call_right_funB = dic_switch[switch_variable].funB(*args)
Hope it helps.

Resources