The `object.from` attribute [duplicate] - python

This question already has answers here:
How do I use a keyword as a variable name?
(3 answers)
Closed 2 years ago.
I have stumbled upon the following syntax error with my Python3 interpreter:
class Class:
pass
a = Class()
a.from = 2
a.from = 2
^
SyntaxError: invalid syntax
Assignment of attributes that do not contain .from seem to be working fine:
a = Class()
a.fro = 2
print(a.__dict__)
{'fro': 2}
I understand that the standalone from statement is reserved for imports but struggle to understand why that would matter in the context of a class with the same key in its dict. Can someone explain why the interpreter complains at this point?

Simply because it's a reserved keyword that you can't use as an identifier.
The same issue would arise with e. g. x.in, x.for, x.import,...

Related

Is the colon of Python assigning a value?What does Python do in this step? [duplicate]

This question already has answers here:
What are variable annotations?
(2 answers)
Closed 2 years ago.
I saw a novel Python syntax,like this
test:[123,"abc"]
test:"123"
But is not a Assignment of variables.
print(test)
NameError Traceback (most recent call last)
in
----> 1 print(test)
NameError: name 'test' is not defined
What does Python do in this step?
what you saw probably was a dictionary like this :
exmaple_dict = {
"test": [123, "abc"],
"test2": "123"
}
see https://www.w3schools.com/python/python_dictionaries.asp for more information.
Contrary to another answer this is actually valid python code!
This is called a type-hint as specified in PEP-484.
Basically it tells the programmer and IDE what type a variable should be but has no effect at runtime.
When you only type test:"abc" (equal to test:str) it does not actually define test, so you get a NameError when you try to acces test later

Use of isinstance(variable,data_type_name) function for NoneType data type gone wrong [duplicate]

This question already has answers here:
How to access the NoneType type?
(2 answers)
Closed 3 years ago.
Suppose a variable is defined:
a=None
On running below code:
print(isinstance(a,NoneType))
gave error: NameError: name 'NoneType' is not defined
For any other data type, its working correctly
print(isinstance(5,int), isinstance(4.0,float), isinstance(False,bool), isinstance("on_and_on",str), isinstance([1,"2",3.0,True,None],list), isinstance((1,"2",3.0,True,None),tuple), isinstance({4,1,3,2},set), isinstance({1:"a","apple":2,5.0:True},dict), isinstance(5-2j,complex))
Why?
you need to declare the type:
isinstance(a, type(None))
### result:
True
or just use a bool check:
a=None
if a is None:
print("a is NoneType")
### result:
a is None type
see also this post if you're interested in some theory.

How can I pass the name of `ObjectName` like `self.lineEdit_260` as a parameter in a method using python 3.4? [duplicate]

This question already has answers here:
Argument 1 has unexpected type 'NoneType'?
(2 answers)
Closed 3 years ago.
How can I pass the name of ObjectName like self.lineEdit_260 as a parameter in a method using python 3.4?
self.Open_Fan_J104_A_stage_2(no=self.lineEdit_260.text()))
def Open_Fan_J104_A_stage_2(self,no):
if no=='' and self.lineEdit_247.text()=='':
print(type(self.lineEdit_260.text()))
self.start_time=datetime.datetime.now()
self.lineEdit_260.setText(str(self.start_time))
elif self.lineEdit_247.text()=='':
QMessageBox.information(self, 'x')
else:
self.lineEdit_260.setText('')
self.start_time = datetime.datetime.now()
self.lineEdit_260.setText(str(self.start_time))
self.lineEdit_247.setText('')
self.lineEdit_241.setText('')
When I run this code:
self.pushButton_123.clicked.connect( self.Open_Fan_J104_A_stage_2(no=self.lineEdit_260.text()))
TypeError: argument 1 has unexpected type 'NoneType'
I think, the Open_Fan_J104_A_stage_2 expects a callable and since there was a lack of information. So try,
self.Open_Fan_J104_A_stage_2(lambda: self.lineEdit_260.text()))

Python Class shows name not defined [duplicate]

This question already has answers here:
Python - Why is this class variable not defined in the method?
(3 answers)
Why is instance variable not getting recognized
(2 answers)
Closed 6 years ago.
I am writing a piece of code for a homework class, which should allow me to calculate various distance statistics about two lists. However, when I assign the lists to the class, and try to print the result of one of the functions, I get the error,
NameError: name 'ratings1' is not defined
Leading me to believe that I did something incorrectly either in my __init__ function or the referencing in the functions. Can you help clarify what I'm doing wrong?
class similarity:
def __init__(self, ratingX, ratingY):
self.ratings1=ratingX
self.ratings2=ratingY
def minkowski(self,r):
self.r=r
mink=0
length=len(ratings1)
for i in range(0,length):
mink=mink+(abs(ratings1[i]-ratings2[i]))**r
mink=mink**(1/r)
result='Given r=%d, Minkowski distance=%f'%(r,mink)
return result
def pearson(self):
Xavg=average(ratings1)
Yavg=average(ratings2)
n=len(ratings1)
diffX=[]
diffY=[]
for i in range(0,n):
diffX.append(ratings1[i]-Xavg)
diffY.append(ratings2[i]-Yavg)
return diffX
diffXY=[]
for i in range(0,n):
diffXY.append(diffX[i]*diffY[i])
example2=similarity([1,3,5,5,6],[4,6,10,12,13])
print(example2.pearson())
Note: this error persists if I change the references to "ratings1/2" to "ratingsX/Y" in the functions.
You need to use self before every reference to instance variable, ie self.ratings1, and your indentation is wrong as well.
ratings are associated with class. Use self.ratings1 and so on..
I just figured out my mistake. For each function I failed to use the self. phrase before the ratings name. To amend this, I added
ratings1=self.
ratings2=self.ratings2
To the beginning of each function. Problem solved.

Website to check Illegal variable names or keywords Python [duplicate]

This question already has an answer here:
Why is it a syntax error to have an object attribute named "del", "return" etc?
(1 answer)
Closed 7 years ago.
I may have stumbled on an illegal variable name
pass = "Pass the monkey!"
print pass
Syntax error: invalid syntax
I'm aware that some keywords are verboten as variables.
Is there the Pythonic equivalent to JavaScript variable name validator?
You can test whether something is a keyword or not using the keyword module
>>> import keyword
>>> keyword.iskeyword("pass")
True
>>> keyword.iskeyword("not_pass")
False
https://docs.python.org/2/library/keyword.html
This module allows a Python program to determine if a string is a
keyword.
keyword.iskeyword(s)
Return true if s is a Python keyword.
Some variable names are illegal in Python because of it being a reserved word.
From the keywords section in the Python docs:
The following identifiers are used as reserved words, or keywords of
the language, and cannot be used as ordinary identifiers. They
must be spelled exactly as written here:
# Complete list of reserved words
and
del
from
not
while
as
elif
global
or
with
assert
else
if
pass
yield
break
except
import
print
class
exec
in
raise
continue
finally
is
return
def
for
lambda
try
True # Python 3 onwards
False # Python 3 onwards
None # Python 3 onwards
nonlocal # Python 3 onwards
async # in Python 3.7
await # in Python 3.7
So, you cannot use any of the above identifiers as a variable name.
This function will check if a name is a keyword in Python or one of Python built-in objects, which can be a function, a constant, a type or an exception class.
import keyword
def is_keyword_or_builtin(name):
return keyword.iskeyword(name) or name in dir(__builtins__)
While you can't use Python keywords as variable names, you are allowed to do it with Python built-ins though it's considered a bad practice so I will recommend to avoid it.

Categories

Resources