Why '' in variable length arguments? - python

I got an error from this code:
def func(**num):
x = num[a] + num[b] + num[c]
print(x)
func(a=2, b=3, c=4)
The error is this:
Traceback (most recent call last):
File "(erased)", line 4, in <module>
func(a=2, b=3, c=4)
File "(erased)", line 2, in func
x = num[a] + num[b] + num[c]
NameError: name 'a' is not defined
Please explain it why a, b, and c in num[] requires to be put between ''?

Related

TypeError: 'NoneType' object is not iterable in Phyton

My program removes the substring 'rotten' from the string list:
bag_of_fruits = ["apple","rottenBanana","apple"]
def remove_rotten(bag_of_fruits):
bag_of_fruits = [x.removeprefix('rotten') for x in bag_of_fruits]
return [x.lower() for x in bag_of_fruits]
print(remove_rotten(bag_of_fruits))
All tests is completed, but in the end program shows 'Unexpected exception raised':
Traceback (most recent call last):
File "/workspace/default/.venv/lib/python3.10/site-packages/codewars_test/test_framework.py", line 112, in wrapper
func()
File "/workspace/default/tests.py", line 21, in fixed_tests
test.assert_equals(remove_rotten(tst[0]), tst[1], f"Input = {tst[0]}")
File "/workspace/default/solution.py", line 4, in remove_rotten
bag_of_fruits = [x.removeprefix('rotten') for x in bag_of_fruits]
TypeError: 'NoneType' object is not iterable
Try to change the name of the variable to avoid the error
bag_of_fruits = ["apple","rottenBanana","apple"]
def remove_rotten(bag_of_fruits):
# ---- > variable name should be changed
bag_of_fruits_edited = [x.removeprefix('rotten') for x in bag_of_fruits]
return [x.lower() for x in bag_of_fruits_edited]
print(remove_rotten(bag_of_fruits))

Pass different initarg to different worker in ProcessPoolExecutor

In [5]: def fn(x):
...: os.environ["var_{}".format(x)] = x
...:
...:
[PYFLYBY] import os
In [6]: def gn(x):
...: return os.environ["var_{}".format(x)]
...:
...:
...:
a = ["1", "2", "3"]
In [8]: with concurrent.futures.ProcessPoolExecutor(max_workers=3, initializer=fn, initargs=a) as e:
...: r = e.map(gn, a)
...:
Exception in initializer:
Traceback (most recent call last):
File "/opt/python/python-3.7/lib64/python3.7/concurrent/futures/process.py", line 226, in _process_worker
initializer(*initargs)
TypeError: fn() takes 1 positional argument but 3 were given
Exception in initializer:
Traceback (most recent call last):
File "/opt/python/python-3.7/lib64/python3.7/concurrent/futures/process.py", line 226, in _process_worker
initializer(*initargs)
TypeError: fn() takes 1 positional argument but 3 were given
Exception in initializer:
Traceback (most recent call last):
File "/opt/python/python-3.7/lib64/python3.7/concurrent/futures/process.py", line 226, in _process_worker
initializer(*initargs)
TypeError: fn() takes 1 positional argument but 3 were given
So, basically, I want a[0] to be passed to first worker, a[1] to the second and so on... is there any way to accomplish this in this way? Right now, entire a is being passed to fn, which is causing this error.
Your example is not entirely correct, but as for the question:
You can pass a multiprocessing.Queue to initializer function, put to it worker specific data and do one queue.get() in each worker process:
import os
import concurrent.futures
import multiprocessing
import time
def fn(q):
x = q.get()
os.environ["var_x"] = x
def gn(i):
time.sleep(0.5)
return f"pid={os.getpid()} var_x={os.environ['var_x']}\n"
q = multiprocessing.Queue()
a = ["1", "2", "3"]
with concurrent.futures.ProcessPoolExecutor(max_workers=3, initializer=fn, initargs=(q,)) as e:
[q.put(i) for i in a]
print(*e.map(gn, a))
Output:
pid=1218 var_x=1
pid=1219 var_x=2
pid=1220 var_x=3

TypeError: object of type 'int' has no len() when using sop.brute

I use the Python3.6 and I've been confused about this question for a long time..so here is my code.
def fo(x,y):
z=np.sin(x)+0.05*x**2+np.cos(y)+0.05*y**2
if output == True:
print("%8.4f %8.4f %8.4f" % (x,y,z))
return z
import scipy.optimize as sop
sop.brute(fo,(-10,10.1,5),(-10,10.1,5),finish = None)
Here is the error I get:
Traceback (most recent call last):
File "<ipython-input-12-c7886e35ff4b>", line 1, in <module>
sop.brute(fo,(-10,10.1,5),(-10,10.1,5),finish = None)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 2811, in brute
if len(lrange[k]) < 3:
TypeError: object of type 'int' has no len()
here's another try:
r1=slice(-10,10.1,5)
r2=slice(-10,10.1,5)
sop.brute(fo,r1,r2,finish = None)
and the error:
Traceback (most recent call last):
File "<ipython-input-48-230c07265998>", line 1, in <module>
sop.brute(fo,r1,r2,finish = None)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 2804, in brute
N = len(ranges)
TypeError: object of type 'slice' has no len()
sop.brute(fo,(r1,r2),finish = None)
TypeError: fo() missing 1 required positional argument: 'y'
I'm new to here and sorry if I ask a stupid question but I cant' work it out T.T thx a lot
def fo(p):
x, y = p
z = np.sin(x)+0.05*x**2+np.sin(y)+0.05*y**2
if output == True:
print('%8.4f %8.4f %8.4f' % (x,y,z))
return z
unpack tuple like in the code

How to obtain full stack trace after exception from function passed as parameter?

I have wrapper function, that takes other function as parameter, catches an exception and does something with it:
def exceptionCatchingWrapper(funcToCall,destForException,*args,**kwargs):
try:
r=funcToCall(*args,**kwargs)
except:
destForException["exc_info"]=sys.exc_info()
else:
return r
I realized that when an exception is caught, the stack trace taken from sys.exc_info() contains only information about exceptionCatchingWrapper() itself and nothing deeper. Is it possible and how to obtain full stack trace after such call?
import traceback
def a(x):
b(x)
def b(x):
x/0
d = {}
exceptionCatchingWrapper(a, d, 10)
Traceback is stored in the dictionary:
>>> traceback.print_tb(d['exc_info'][2]
File "<stdin>", line 3, in exceptionCatchingWrapper
File "<stdin>", line 2, in a
File "<stdin>", line 2, in b
>>> traceback.print_exception(d['exc_info'][0],d['exc_info'][1],d['exc_info'][2])
Traceback (most recent call last):
File "<stdin>", line 3, in exceptionCatchingWrapper
File "<stdin>", line 2, in a
File "<stdin>", line 2, in b
ZeroDivisionError: integer division or modulo by zero
More information in the traceback module documentation.
Not sure if this is what you need but these might be a way you can print the traceback:
import traceback
try:
s += 1 #this doesnt exist yet
except:
a = traceback.format_exc()
print a
-or-
import traceback, sys
def DummyFunc2():
s += 1 #this doesnt exist yet
def DummyFunc1():
DummyFunc2()
try:
DummyFunc1()
except:
_, err, tb = sys.exc_info()
tb_lines = traceback.extract_tb(tb)
for idx, trace in enumerate( traceback.format_list(tb_lines) ):
print "[INDEX %d]\n%s" % (idx,trace)
print err
output:
>>>
[INDEX 0]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 9, in <module>
DummyFunc1()
[INDEX 1]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 6, in DummyFunc1
DummyFunc2()
[INDEX 2]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 4, in DummyFunc2
s += 1 #this doesnt exist yet
local variable 's' referenced before assignment
>>>

GeocoderDotUS Geopy ('NoneType' object is not iterable)

import csv
from geopy import geocoders
import time
g = geocoders.GeocoderDotUS()
spamReader = csv.reader(open('locations.csv', 'rb'), delimiter='\t', quotechar='|')
f = open("output.txt",'w')
for row in spamReader:
a = ', '.join(row)
#exactly_one = False
time.sleep(1)
place, (lat, lng) = g.geocode(a)
b = str(place) + "," + "[" + str(lat) + "," + str(lng) + "]" + "\n"
print b
f.write(b)
I can't really determine why I am receiving
Traceback (most recent call last):
File "C:\Users\Penguin\workspace\geocode-nojansdatabase\src\yahoo.py", line 17, in
place, (lat, lng) = g.geocode(a)
TypeError: 'NoneType' object is not iterable
I checked to make sure there was a value in a before the geocode(a) call was placed. Perhaps a match was not found? If that is the case the I guess I just have to add in an if not b then statement. Does anyone know more about this?
I am seeing that adding a
a = ', '.join(row)
print(a)
Does yield:
178 Connection Rd Pomona QLD
>>> a, (b, c) = None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
>>> a, (b, c) = ('foo', None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
Your guess is correct. Check before unpacking.

Categories