-1

I need to check, whether variable is defined or not. If it is not, then this variable should be created as empty string. I want to do it by try and it works fine:

try:
    ident
except:
    ident = ''

But I need to do that using a function, coz I will do that many, many times and it will became unreadable.

Doing it like below can't work, coz it will not go into the function, if ident does not exist.

def absence_of_tag(ident):
    try:
        ident
    except:
        return ''

I was also trying to do it with *args, like that:

def absence_of_tag(*args):
    try:
        args
    except:
        return ''

and then call it by:

ident = absence_of_tag(ident)

I thought, it will go into the except in function, but still it gave me NameError: name 'ident' is not defined

Do you have any idea how to do that? Is it even possible?

GohanP
  • 399
  • 2
  • 6
  • 18
  • 1
    possible duplicate: https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists – Joe Jul 19 '17 at 13:37
  • you can check `globals()` and `locals()` for the variable if you have its name as a string. So `'ident' in globals()` would return true if a variable named `ident` exists in the global scope. However, why do you even need this? Usually, one should avoid using variables that aren't defined in every case. – Zinki Jul 19 '17 at 13:40
  • 3
    You should not need to check whether variables exist or not all that much anyway; you should ensure your variables are initialised and then not worry about it. Further, your example use case with "the def" is a completely different issue. If `ident` in `absence_of_tag(ident)` is not defined (in the caller), there's nothing the body of that function can do about it. – deceze Jul 19 '17 at 13:40
  • Please stop calling this a "def" or a "definition". It's a function. – Daniel Roseman Jul 19 '17 at 13:44

1 Answers1

0

If you want a one-liner, you can perhaps go with:

ident= ident if ident else ' '

EDIT: This also worked for me:

f=lambda x: x if x else ' '

c=8

f(c)     
# output: 8

f(d)    
# NameError: name 'd' is not defined
Jay
  • 2,535
  • 3
  • 32
  • 44