Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Treat error ?
#1
The code below checks for the existence of a method belonging to a class. If the method exists it returns me True and if it does not return the following error (AttributeError: type object 'Runcode' has no attribute 'scree'), I tried to deal with (AttributeError) to obtain the result False, being that it persists in the error (AttributeError: type object 'Runcode' has no attribute 'scree'). I know that this error is due to the value of the method that was declared wrong on purpose just to be able to get the Boolean value False, being that I can't get it ?

# Acessar a classe controller e checa a existencia do method :
o_metexist = hasattr("Runcode", "scree")

try:
    # Return, dispara o evento de acesso ao method da class importada :
    print(o_metexist)

except AttributeError:
    #
    v_false = "False"
    #
    print(v_false)
Reply
#2
class Foo:
    def spam(self):
        pass

    
try:
    check = hasattr(Foo, 'eggs')
except AttributeError:
    check = False

print(check)
print(hasattr(Foo, 'spam'))


I was misled by your AttributeError...

you don't need try/except

class Foo:
    def spam(self):
        pass

check = hasattr(Foo, 'eggs')
print(check)
check = hasattr(Foo, 'spam')
print(check)
As a side note about using try/except - try should be before the line that may raise error, not after that.

try:
    print(1/0)
except ZeroDivisionError:
    print('Cannot divide by 0')
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Apr-14-2020, 07:49 PM)buran Wrote:
class Foo:
    def spam(self):
        pass

    
try:
    check = hasattr(Foo, 'eggs')
except AttributeError:
    check = False

print(check)
print(hasattr(Foo, 'spam'))


I was misled by your AttributeError...

you don't need try/except

class Foo:
    def spam(self):
        pass

check = hasattr(Foo, 'eggs')
print(check)
check = hasattr(Foo, 'spam')
print(check)
As a side note about using try/except - try should be before the line that may raise error, not after that.

try:
    print(1/0)
except ZeroDivisionError:
    print('Cannot divide by 0')

I redid the code assigning the egg value in a variable and it generates an error instead of false?

class Foo:
    def spam(self):
        pass
    v_method = "egg"
    check = hasattr(Foo, v_method)
    print(check)
Reply
#4
I have no idea what are you doing to get the error. The code you show does nothing because lines 4-6 are inside class you never use. Fix indentation and it works.
Here is the code in repl.it
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(Apr-15-2020, 05:02 PM)buran Wrote: I have no idea what are you doing to get the error. The code you show does nothing because lines 4-6 are inside class you never use. Fix indentation and it works.
Here is the code in repl.it

Will I try to give a better understanding?

I have the following code below that aims to access module's dynamically:

# Native module import: import_module
from importlib import import_module

appget = "website"
conget = "Runcode"
metget = "screen"

# Import dynamic module: activating the controller and the standard method:
pathmod = "apps". + appget + ".controllers." + conget
# Import dynamic module: passing as parameter or path assigned in the variable:
modulo = import_module (pathmod)
# Retrieve a class: last as attractive parameters in the class-controller variable:
class = getattr (module, conget)
# Retrieve the method: passed, as a parameter assigned to the method-controller variable:
method = getattr (class, metget)
# Instance or object: related to the class method:
output = method ()
# Return :
print (output)
So far so good the code above runs perfectly.

The problem is that I need to get the boolean result of the class method, I tried to do this using the python hasattr method, managing to get the Boolean value True, but if the class method does not exist (any other) I get the following error message:

Existing Method: True
# Access the controller class and check the existence of the method:
metexist = hasattr (class, metget)
# Return :
print (metexist) # I get True
Method does not exist: Error message in the terminal
o_method = getattr (o_class, v_metget)
AttributeError: type object 'Runcode' has no attribute 'other'
How can I get the boolean value as False, as opposed to the error message?
Reply
#6
o_method = getattr (o_class, v_metget)
AttributeError: type object 'Runcode' has no attribute 'other'
In your code you don't try to check for "other". Please, post full traceback and the actual code that produce the error.

(Apr-16-2020, 10:28 AM)JohnnyCoffee Wrote: So far so good the code above runs perfectly.

There are couple of issues with your code, line 13. It's not possible your code is actually running:
class = getattr (module, conget)
1. class is reserved word, so it's not possible to assign to it (use it as variable name). This will raise SynatxError.
>>> class = 'foo'
  File "<stdin>", line 1
    class = 'foo'
          ^
SyntaxError: invalid syntax
>>>
2 module is not defined and will result in NameError.


Here is working example
>>> from importlib import import_module
>>> my_module = import_module('csv')
>>> my_attr = 'DictReader'
>>> test = hasattr(my_module, my_attr)
>>> test
True
>>> my_attr = 'NoExist'
>>> test = hasattr(my_module, my_attr)
>>> test
False
>>>
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
(Apr-16-2020, 11:40 AM)buran Wrote:
o_method = getattr (o_class, v_metget)
AttributeError: type object 'Runcode' has no attribute 'other'
In your code you don't try to check for "other". Please, post full traceback and the actual code that produce the error.

(Apr-16-2020, 10:28 AM)JohnnyCoffee Wrote: So far so good the code above runs perfectly.

There are couple of issues with your code, line 13. It's not possible your code is actually running:
class = getattr (module, conget)
1. class is reserved word, so it's not possible to assign to it (use it as variable name). This will raise SynatxError.
>>> class = 'foo'
  File "<stdin>", line 1
    class = 'foo'
          ^
SyntaxError: invalid syntax
>>>
2 module is not defined and will result in NameError.


Here is working example
>>> from importlib import import_module
>>> my_module = import_module('csv')
>>> my_attr = 'DictReader'
>>> test = hasattr(my_module, my_attr)
>>> test
True
>>> my_attr = 'NoExist'
>>> test = hasattr(my_module, my_attr)
>>> test
False
>>>

I had just written it wrong, on line 13 but the problem persists. The analysis you mentioned refers to checking the module and class. In my case it is to check if the class method exists and then I face the error ?
Reply
#8
I give up. My example is doing exactly what your "working", but actually not working example, for existing and non-existing attribute. You keep saying that the problem persist, but never show actual working code that reproduce the error and full traceback produced.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
(Apr-17-2020, 03:01 AM)buran Wrote: I give up. My example is doing exactly what your "working", but actually not working example, for existing and non-existing attribute. You keep saying that the problem persist, but never show actual working code that reproduce the error and full traceback produced.

buran, i'm sorry if I didn't post the corrected code, I describe below:

# Native Module Import: import_module
from importlib import import_module

v_appget = "website"
v_conget = "runcode"
t_conget = "Runcode"
v_metget = "scree" # method does not exist

# Import dynamic module: calling the controller and pattern method:
v_pathmod = "apps." + v_appget + ".controllers." + v_conget
# Import dynamic module: passing as path the path assigned to the variable:
o_module = import_module (v_pathmod)
# Retrieve the class: passed as an attribute parameter in the class-controller variable:
o_class = getattr (o_module, t_conget)
# Retrieve the method: passed as an attribute parameter in the method-controller variable:
o_method = getattr (o_class, v_metget, None)
# Instantiate the object: related to the class method:
o_return = o_method ()
# Access the controller class and check the existence of the method:
o_metexist = hasattr (o_class, v_metget)
# Output:
print (o_metexist)
Thus it generates the error, because the method of the class does not exist according to the variable (v_metget), above. The idea would be to obtain the Boolean False result instead of the error below:

o_return = o_method()
TypeError: 'NoneType' object is not callable
Reply
#10
You were asking about hasattr, your code example uses getattr.
Your code is fine up to line 14. from there on, line by line:
o_method = getattr (o_class, v_metget, None)
you try to get non-existing method. You also supply optional default value of None.

o_return = o_method ()
o_return is None, but you try to call it, so you get the current error - TypeError, which is different from the original error you had - AttributeError. I guess in your original code you were not supplying None.

So you can do three things, one is to use hasattr, as per your initial question:
# Native Module Import: import_module
from importlib import import_module
 
v_appget = "website"
v_conget = "runcode"
t_conget = "Runcode"
v_metget = "scree" # method does not exist
 
# Import dynamic module: calling the controller and pattern method:
v_pathmod = "apps." + v_appget + ".controllers." + v_conget
# Import dynamic module: passing as path the path assigned to the variable:
o_module = import_module (v_pathmod)
# Retrieve the class: passed as an attribute parameter in the class-controller variable:
o_class = getattr (o_module, t_conget)
# Retrieve the method: passed as an attribute parameter in the method-controller variable:
has_o_method = hasattr(o_class, v_metget)
print(has_o_method) # this will print False
if has_o_method:
    o_method = getattr (o_class, v_metget)
    # Instantiate the object: related to the class method:
    o_return = o_method()
Second is to use the default value of None:
# Native Module Import: import_module
from importlib import import_module
 
v_appget = "website"
v_conget = "runcode"
t_conget = "Runcode"
v_metget = "scree" # method does not exist
 
# Import dynamic module: calling the controller and pattern method:
v_pathmod = "apps." + v_appget + ".controllers." + v_conget
# Import dynamic module: passing as path the path assigned to the variable:
o_module = import_module (v_pathmod)
# Retrieve the class: passed as an attribute parameter in the class-controller variable:
o_class = getattr (o_module, t_conget)
# Retrieve the method: passed as an attribute parameter in the method-controller variable:
o_method = getattr (o_class, v_metget, None)
if o_method: # None is evaluated as False, so if method does not exists, it will skip calling it
    # Instantiate the object: related to the class method:
    o_return = o_method()
The third is to use try/except, i.e. EAFP - Easier to ask for forgiveness than permission, (that would be my preference as more idiomatic python) vs LBYL - Look before you leap, that is what using hasattr approach is.

# Native Module Import: import_module
from importlib import import_module
 
v_appget = "website"
v_conget = "runcode"
t_conget = "Runcode"
v_metget = "scree" # method does not exist
 
# Import dynamic module: calling the controller and pattern method:
v_pathmod = "apps." + v_appget + ".controllers." + v_conget
# Import dynamic module: passing as path the path assigned to the variable:
o_module = import_module (v_pathmod)
# Retrieve the class: passed as an attribute parameter in the class-controller variable:
o_class = getattr (o_module, t_conget)
# Retrieve the method: passed as an attribute parameter in the method-controller variable:
try:
    o_method = getattr (o_class, v_metget, None)
    # Instantiate the object: related to the class method:
    o_return = o_method()
except AttributeError:
    print (f'{o_mtehod} does not exists')
To sum up - Your initial problem with AttributeError was, because you were calling getattr on non-existing method, before callinh hasattr on it.
In the latest example you were getting TypeError, because you were calling getattr with default value of None (this was missing in your initial code).

And note - you show just the final line of traceback, not the whole traceback. Please, always post the full traceback, not just the final line.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to treat two token as one token(lexer)? hsunteik 1 3,589 Dec-28-2016, 12:26 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020