Check if there is object in instantancy

Asked

Viewed 209 times

0

I wonder how I check for variable object in Python.

I tried so:

try:
  select_me = User.select_me(request)
  select_random = User.select_random(request, 3)

  me = select_me.username
  random = select_random.username
  gender = select_random.gender
except:
  me = 'Error'
  random = 'Error'
  gender = 'Error'

But I think, you know, I think you can sort this out, for example, "shorten"

In Python, there is some function to check if there is an object inside that variable?

PS: Without the treatment with try and except he throws me:

'Nonetype' Object has no attribute 'username'

in PHP a if (is_object(...)) would solve, and in Python?

Something with if or else or even some native Python function, has as?

  • What are the possible function returns User.select_me? An object User or None?

  • @Andersoncarloswoss, returns, username, name, lastname...

1 answer

0


Whether the call can return an object or None, you compare by checking if the returned object is None with the operator is:

select_me = User.select_me(request)
if select_me is None:
   me, random, gender = "Error"
else:
   ...

Note that comparison with use of is should only be done in special cases - such as None, or when using the Sentinel Pattern . If it is a call that can return an empty string, or an empty list you simply check the "Truth value" of the returned object - (any empty container or numeral == 0, or None will be False in Python - all other objects are True) - in that case, the expression no if is the object itself (or the not of the object):

select_me = User.select_me(request)
if not select_me:
   me, random, gender = "Error"
else:
   ...

In case you don’t know if a variable has already been defined - for example, if it is defined only within a block of if not executed - recommended in Python is to set the variable before the if - that is to say, instead of:

if tudo_ok():
    conexao = conectar()

...
# não há uma verificação para "undefined"
conexao.usar

do:


conexao = None
if tudo_ok():
    conexao = conectar()

...
if conexao is not None:
    conexao.usar

For this case, (the variable is not set), it would work to put the code that will use the variable you do not know if it is set in a block try and capture the exception NameError in the clause except - but this is not good practice.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.