Why NameError here - python-3.x

Why I am getting this error, actually I have already defined ' a' before using in both codes.
def add(a,b):
return a+b
kwargs={'a':3,'b':5,'c':add(a,b)}
print("a is {a},b is {b}".format(**kwargs))
Traceback (most recent call last):
File "E:\GitRepo\Advanced_Python\logNew.py", line 13, in <module>
kwargs={'a':3,'b':5,'c':add(a,b)}
NameError: name 'a' is not defined
import logging
logging.basicConfig(level=logging.INFO)
def add(a,b):
return a+b
logging.info("Summation of {a},{b} is {c}".format(a=3,b=4,c=add(a,b)))
Traceback (most recent call last):
File "E:\GitRepo\Advanced_Python\logNew.py", line 5, in <module>
logging.info("Summation of {a},{b} is {c}".format(a=3,b=4,c=add(a,b)))
NameError: name 'a' is not defined

def add(a,b):
return a+b
kwargs={'a':3,'b':5}
kwargs['c']=add(kwargs['a'],kwargs['b'])
print("a is {a},b is {b}".format(**kwargs))
you have to write like this , a is not variable here, it is constant 'a'.
import logging
logging.basicConfig(level=logging.INFO)
def add(a,b):
return a+b
a=3
b=4
logging.info("Summation of {a},{b} is {c}".format(a=a,b=b,c=add(a,b)))
you have to declare variables first then use it.

When the python interpreter encounters the line: kwargs={'a':3,'b':5,'c':add(a,b)}. This is what it does:
Evaluate all the values of the keys being assigned to
This includes 3, 5 and add(a, b)
3 & 5 get defined as usual - since those are constants
add(a, b) - here add is defined (the function you defined above)
But a or b are not defined!
Hence the error. a & b are not variables (you can check this by checking the locals() & globals() - variables should show up there). They are keys in the dictionary.
This will work:
def add(a,b):
return a+b
a = 3
b = 5
kwargs={'a':a,'b':b,'c':add(a,b)}
print("a is {a},b is {b}".format(**kwargs))
Because the variables a & b are defined before add(a, b) is evaluated.

Your "add" function is expecting two integers, but you are not giving it when in dictionary expression. Look:
def add(a,b):
return a+b
kwargs={'a':3,'b':5,'c':add(5,2)}
print("a is {a},b is {b}".format(**kwargs))
I am passing 5 and 2 in dictionary expression.
Hope this helps.

Related

'int' object is not callable (about closure)

today I learn some python.
When I try to write some code, I had some questions.
def outer(a, b):
def inner():
return a+b
return inner
a=outer(4, 3)
print(a)
print(a())
<function outer.<locals>.inner at 0x0000028F37C519D0
7
and this code
def outer2(a, b):
def inner2(c, d):
return c + d
return inner2(a, b)
b = outer2(4,3)
print(b)
print(b())
7
TypeError Traceback (most recent call last) <ipython-input-41-b2c9e3844269> in <module> 5 b = outer2(4,3) 6 print(b) ----> 7 print(b()) TypeError: 'int' object is not callable
I really want to know difference between a and b , anyone can help me? Thank you very much
The problem lies in this line : return inner2(a, b)
what you did was:
You are actually invoking a function inner2(c,d) and passing an argument to it.Which will eventually return an integer.
what you should do instead:
Do not invoke a function with arguments, just return the reference : return inner2.
You code should look something like this now:
def outer2(a, b):
def inner2():
return a + b
return inner2
#b now holds the reference to a function inner2()
b = outer2(4,3)
#prints the reference to the function object
print(b)
#invokes the function inner2 and use the arguments a,b from an outer function.
print(b())
This is called currying in python i.e, a function returning another function: Here to get some ideas

Decorators or assertions in setters to check property type?

In a python project, my class has several properties that I need to be of specific type. Users of the class must have the ability to set the property.
What is the best way to do this? Two solutions come to my mind:
1. Have test routines in each setter function.
2. Use decorators for attributes
My current solution is 1 but I am not happy with it due to the code duplication. It looks like this:
class MyClass(object):
#property
def x(self):
return self._x
#x.setter
def x(self, val):
if not isinstance(self, int):
raise Exception("Value must be of type int")
self._x = val
#property
def y(self):
return self._y
#x.setter
def y(self, val):
if not isinstance(self, (tuple, set, list)):
raise Exception("Value must be of type tuple or set or list")
self._y = val
From what I know of decorators, it should be possible to have a decorator before def x(self) handle this job. Alas I fail miserably at this, as all examples I found (like this or this) are not targeted at what I want.
The first question is thus: Is it better to use a decorator to check property types? If yes, the next question is: What is wrong with below decorator (I want to be able write #accepts(int)?
def accepts(types):
"""Decorator to check types of property."""
def outer_wrapper(func):
def check_accepts(prop):
getter = prop.fget
if not isinstance(self[0], types):
msg = "Wrong type."
raise ValueError(msg)
return self
return check_accepts
return outer_wrapper
Appetizer
Callables
This is likely beyond your needs, since it sounds like you're dealing with end-user input, but I figured it may be helpful for others.
Callables include functions defined with def, built-in functions/methods such as open(), lambda expressions, callable classes, and many more. Obviously, if you only want to allow a certain type(s) of callables, you can still use isinstance() with types.FunctionType, types.BuiltinFunctionType, types.LambdaType, etc. But if this is not the case, the best solution to this that I am aware of is demonstrated by the MyDecoratedClass.z property using isinstance() with collections.abc.Callable. It's not perfect, and will return false positives in extraordinary cases (for example, if a class defines a __call__ function that doesn't actually make the class callable). The callable(obj) built-in is the only foolproof check function to my knowledge. The MyClass.z the use property demonstrates this function, but you'd have to write another/modify the existing decorator function in MyDecoratedClass in order to support the use of check functions other than isinstance().
Iterables (and Sequences and Sets)
The y property in the code you provided is supposed to be restricted to tuples, sets, and lists, so the following may be of some use to you.
Instead of checking if arguments are of individual types, you might want to consider using Iterable, Sequence, and Set from the collections.abc module. Please use caution though, as these types are far less restrictive than simply passing (tuple, set, list) as you have. abc.Iterable (as well as the others) work near-perfectly with isinstance(), although it does sometimes return false positives as well (e.g. a class defines an __iter__ function but doesn't actually return an iterator -- who hurt you?). The only foolproof method of determining whether or not an argument is iterable is by calling the iter(obj) built-in and letting it raise a TypeError if it's not iterable, which could work in your case. I don't know of any built-in alternatives to abc.Sequence and abc.Set, but almost every sequence/set object is also iterable as of Python 3, if that helps. The MyClass.y2 property implements iter() as a demonstration, however the decorator function in MyDecoratedClass does not (currently) support functions other than isinstance(); as such, MyDecoratedClass.y2 uses abc.Iterable instead.
For the completeness' sake, here is a quick comparison of their differences:
>>> from collections.abc import Iterable, Sequence, Set
>>> def test(x):
... print((isinstance(x, Iterable),
... isinstance(x, Sequence),
... isinstance(x, Set)))
...
>>> test(123) # int
False, False, False
>>> test("1, 2, 3") # str
True, True, False
>>> test([1, 2, 3]) # list
(True, True, False)
>>> test(range(3)) # range
(True, True, False)
>>> test((1, 2, 3)) # tuple
(True, True, False)
>>> test({1, 2, 3}) # set
(True, False, True)
>>> import numpy as np
>>> test(numpy.arange(3)) # numpy.ndarray
(True, False, False)
>>> test(zip([1, 2, 3],[4, 5, 6])) # zip
(True, False, False)
>>> test({1: 4, 2: 5, 3: 6}) # dict
(True, False, False)
>>> test({1: 4, 2: 5, 3: 6}.keys()) # dict_keys
(True, False, True)
>>> test({1: 4, 2: 5, 3: 6}.values()) # dict_values
(True, False, False)
>>> test({1: 4, 2: 5, 3: 6}.items()) # dict_items
(True, False, True)
Other Restrictions
Virtually all other argument type restrictions that I can think of must use hasattr(), which I'm not going to get into here.
Main Course
This is the part that actually answers your question. assert is definitely the simplest solution, but it has its limits.
class MyClass:
#property
def x(self):
return self._x
#x.setter
def x(self, val):
assert isinstance(val, int) # raises AssertionError if val is not of type 'int'
self._x = val
#property
def y(self):
return self._y
#y.setter
def y(self, val):
assert isinstance(val, (list, set, tuple)) # raises AssertionError if val is not of type 'list', 'set', or 'tuple'
self._y = val
#property
def y2(self):
return self._y2
#y2.setter
def y2(self, val):
iter(val) # raises TypeError if val is not iterable
self._y2 = val
#property
def z(self):
return self._z
#z.setter
def z(self, val):
assert callable(val) # raises AssertionError if val is not callable
self._z = val
def multi_arg_example_fn(self, a, b, c, d, e, f, g):
assert isinstance(a, int)
assert isinstance(b, int)
# let's say 'c' is unrestricted
assert isinstance(d, int)
assert isinstance(e, int)
assert isinstance(f, int)
assert isinstance(g, int)
this._a = a
this._b = b
this._c = c
this._d = d
this._e = e
this._f = f
this._g = g
return a + b * d - e // f + g
Pretty clean overall, besides the multi-argument function I threw in there at the end, demonstrating that asserts can get tedious. However, I'd argue that the biggest drawback here is the lack of Exception messages/variables. If the end-user sees an AssertionError, it has no message and is therefore mostly useless. If you write intermediate code that could except these errors, that code will have no variables/data to be able to explain to the user what went wrong. Enter the decorator function...
from collections.abc import Callable, Iterable
class MyDecoratedClass:
def isinstance_decorator(*classinfo_args, **classinfo_kwargs):
'''
Usage:
Always remember that each classinfo can be a type OR tuple of types.
If the decorated function takes, for example, two positional arguments...
* You only need to provide positional arguments up to the last positional argument that you want to restrict the type of. Take a look:
1. Restrict the type of only the first argument with '#isinstance_decorator(<classinfo_of_arg_1>)'
* Notice that a second positional argument is not required
* Although if you'd like to be explicit for clarity (in exchange for a small amount of efficiency), use '#isinstance_decorator(<classinfo_of_arg_1>, object)'
* Every object in Python must be of type 'object', so restricting the argument to type 'object' is equivalent to no restriction whatsoever
2. Restrict the types of both arguments with '#isinstance_decorator(<classinfo_of_arg_1>, <classinfo_of_arg_2>)'
3. Restrict the type of only the second argument with '#isinstance_decorator(object, <classinfo_of_arg_2>)'
* Every object in Python must be of type 'object', so restricting the argument to type 'object' is equivalent to no restriction whatsoever
Keyword arguments are simpler: #isinstance_decorator(<a_keyword> = <classinfo_of_the_kwarg>, <another_keyword> = <classinfo_of_the_other_kwarg>, ...etc)
* Remember that you only need to include the kwargs that you actually want to restrict the type of (no using 'object' as a keyword argument!)
* Using kwargs is probably more efficient than using example 3 above; I would avoid having to use 'object' as a positional argument as much as possible
Programming-Related Errors:
Raises IndexError if given more positional arguments than decorated function
Raises KeyError if given keyword argument that decorated function isn't expecting
Raises TypeError if given argument that is not of type 'type'
* Raised by 'isinstance()' when fed improper 2nd argument, like 'isinstance(foo, 123)'
* Virtually all UN-instantiated objects are of type 'type'
Examples:
example_instance = ExampleClass(*args)
# Neither 'example_instance' nor 'ExampleClass(*args)' is of type 'type', but 'ExampleClass' itself is
example_int = 100
# Neither 'example_int' nor '100' are of type 'type', but 'int' itself is
def example_fn: pass
# 'example_fn' is not of type 'type'.
print(type(example_fn).__name__) # function
print(type(isinstance).__name__) # builtin_function_or_method
# As you can see, there are also several types of callable objects
# If needed, you can retrieve most function/method/etc. types from the built-in 'types' module
Functional/Intended Errors:
Raises TypeError if a decorated function argument is not an instance of the type(s) specified by the corresponding decorator argument
'''
def isinstance_decorator_wrapper(old_fn):
def new_fn(self, *args, **kwargs):
for i in range(len(classinfo_args)):
classinfo = classinfo_args[i]
arg = args[i]
if not isinstance(arg, classinfo):
raise TypeError("%s() argument %s takes argument of type%s' but argument of type '%s' was given" %
(old_fn.__name__, i,
"s '" + "', '".join([x.__name__ for x in classinfo]) if isinstance(classinfo, tuple) else " '" + classinfo.__name__,
type(arg).__name__))
for k, classinfo in classinfo_kwargs.items():
kwarg = kwargs[k]
if not isinstance(kwarg, classinfo):
raise TypeError("%s() keyword argument '%s' takes argument of type%s' but argument of type '%s' was given" %
(old_fn.__name__, k,
"s '" + "', '".join([x.__name__ for x in classinfo]) if isinstance(classinfo, tuple) else " '" + classinfo.__name__,
type(kwarg).__name__))
return old_fn(self, *args, **kwargs)
return new_fn
return isinstance_decorator_wrapper
#property
def x(self):
return self._x
#x.setter
#isinstance_decorator(int)
def x(self, val):
self._x = val
#property
def y(self):
return self._y
#y.setter
#isinstance_decorator((list, set, tuple))
def y(self, val):
self._y = val
#property
def y2(self):
return self._y2
#y2.setter
#isinstance_decorator(Iterable)
def y2(self, val):
self._y2 = val
#property
def z(self):
return self._z
#z.setter
#isinstance_decorator(Callable)
def z(self, val):
self._z = val
#isinstance_decorator(int, int, e = int, f = int, g = int, d = (int, float, str))
def multi_arg_example_fn(self, a, b, c, d, e, f, g):
# Identical to assertions in MyClass.multi_arg_example_fn
self._a = a
self._b = b
self._c = c
self._d = d
return a + b * e - f // g
Clearly, multi_example_fn is one place where this decorator really shines. The clutter made by assertions has been reduced to a single line. Let's take a look at some example error messages:
>>> test = MyClass()
>>> dtest = MyDecoratedClass()
>>> test.x = 10
>>> dtest.x = 10
>>> print(test.x == dtest.x)
True
>>> test.x = 'Hello'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 7, in x
AssertionError
>>> dtest.x = 'Hello'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 100, in new_fn
TypeError: x() argument 0 takes argument of type 'int' but argument of type 'str' was given
>>> test.y = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 15, in y
AssertionError
>>> test.y2 = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 23, in y2
TypeError: 'int' object is not iterable
>>> dtest.y = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 100, in new_fn
TypeError: y() argument 0 takes argument of types 'list', 'set', 'tuple' but argument of type 'int' was given
>>> dtest.y2 = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 100, in new_fn
TypeError: y2() argument 0 takes argument of type 'Iterable' but argument of type 'int' was given
>>> test.z = open
>>> dtest.z = open
>>> test.z = None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 31, in z
AssertionError
>>> dtest.z = None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 100, in new_fn
TypeError: z() argument 0 takes argument of type 'Callable' but argument of type 'NoneType' was given
Far superior in my opinion. Everything looks good except...
>>> test.multi_arg_example_fn(9,4,[1,2],'hi', g=2,e=1,f=4)
11
>>> dtest.multi_arg_example_fn(9,4,[1,2],'hi', g=2,e=1,f=4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 102, in new_fn
KeyError: 'd'
>>> print('I forgot that you have to merge args and kwargs in order for the decorator to work properly with both but I dont have time to fix it right now. Absolutely safe for properties for the time being though!')
I forgot that you have to merge args and kwargs in order for the decorator to work properly with both but I dont have time to fix it right now. Absolutely safe for properties for the time being though!
Edit Notice: My previous answer was completely incorrect. I was suggesting the use of type hints, forgetting that they aren't actually ensured in any way. They are strictly a development/IDE tool. They still are insanely helpful though; I recommend looking into using them.

Python 3: Invalid Syntax Error when using * operator in __init__ between pre-defined values defined in-scope

I am getting a syntax error when trying to do the following MCVE in Python 3.
HEIGHT = 26
WIDTH = 26
OTHERVAR = 5
class Foo():
def __init__(self, OTHERVAR, HEIGHT*WIDTH):
print (str(OTHERVAR + HEIGHT*WIDTH))
foo_inst = Foo()
Below is the error
File "a.py", line 6
def __init__(self, OTHERVAR, HEIGHT*WIDTH):
^
SyntaxError: invalid syntax
I'm wondering why the multiplication * operator is invalid syntax in this scenario.
If someone could explain why this is bad syntax and offer a potential workaround, that would be great. Thank you.
A function parameter supposes to be a variable, your HEIGHT*WIDTH produces a value, not a variable.
Are you probably looking for this (default value)?
>>> a = 1
>>> b = 2
>>> def test(c=a*b):
... print(c)
...
>>> test()
2
>>> def test(c=a*b, d):
... print(c, d)
...
File "<stdin>", line 1
SyntaxError: non-default argument follows default argument
>>> def test(d, c=a*b):
... print(d, c)
...
>>> test(10)
(10, 2)
And called by named parameters
>>> def test(d, c=a*b, e=20):
... print(d, c, e)
...
>>> test(10, e=30)
(10, 2, 30)

python3 with SQLObject class pass parameters

I am new to python3 and tring to build a sqlobject class which named whatever. Then I created a function to caculate the average of one column. Here are parts of the codes.
class whatever(sqlobject.SQLObject):
_connection = connection
f1 = sqlobject.FloatCol()
f2 = sqlobject.FloatCol()
wid=sqlobject.IntCol(default=None)
def avg(col, num):
l1 = []
for i in range(1,num):
e = whatever.get(i).col
l1.append(a)
return statistics.mean(l1)
print (avg(f1, 5))
But it returns the error:
Traceback (most recent call last):
File "test1.py", line 58, in <module>
print (avg(f1, 5))
NameError: name 'f1' is not defined
However, when I directly wrote down the code like this:
class whatever(sqlobject.SQLObject):
_connection = connection
f1 = sqlobject.FloatCol()
f2 = sqlobject.FloatCol()
wid=sqlobject.IntCol(default=None)
l1 = []
for i in range(1,5):
e = whatever.get(i).f1
l1.append(e)
print (statistics.mean(l1))
It works fine. So what should I do with the def avg(col, num) function?
Please note that whatever.get(i).f1 works — this because you name the column explicitly. If you want to get a column by name you have to:
pass the name of the column, i.e. avg('f1', 5);
get the value for the column using getattr.
So the fixed code is:
def avg(col, num):
l1 = []
for i in range(1, num):
e = getattr(whatever.get(i), col)
l1.append(a)
return statistics.mean(l1)
print(avg('f1', 5))
PS. The next error in your code will be NameError: a. What is a? Do you mean e?

UnboundLocalError: local variable 'max_results' referenced before assignment

for _ in range(10):
try:
next_results = search_results['search_metadata']['next_results']
except KeyError or e:
break
kwargs = dict([ kv.split('=')
for kv in next_results[1:].split("&") ])
search_results = twitter_api.search.tweets(**kwargs)
statuses += search_results['statuses']
if len(statuses) > max_results:
break
q = "CrossFit"
results = twitter_search(twitter_api, q, max_results=10)
print (json.dumps(statuses[0], indent=1))
The code posted is not what you ran, as search_results is not defined and execution would stop there. My guess, based on what you posted, is that max_results is not defined when len(statuses) > max_results is executed. In your original code, the loop must be within a function definition. The error message can only occur when a name within a function, defined to be local because it is an assignment target, is used before any assignment. For instance:
>>> def f():
if True: return y
else: y = 1
>>> f()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
f()
File "<pyshell#10>", line 2, in f
if True: return y
UnboundLocalError: local variable 'y' referenced before assignment
Please read and act on this SO mcve help page. What you posted is both incomplete and over-complete (everything after the if statement is superfluous).

Resources