Logo

Programming-Idioms

  • Python
  • Ruby

Idiom #108 Determine if variable name is defined

Print the value of variable x, but only if x has been declared in this program.
This makes sense in some languages, not all of them. (Null values are not the point, rather the very existence of the variable.)

puts x if defined?(x)
if 'x' in locals():
	print(x)

variable name must be quoted.
try:
    x
except NameError:
    print("does not exist")
int x = 42;

void printIfDefined(alias name)()
{
    import std.stdio: writeln;
    static if( __traits(compiles, writeln(mixin(name))))
        writeln(mixin(name));
}

void main(string[] args)
{
    printIfDefined!"x";
    printIfDefined!"Foo.bar";
}

The string is turned into its equivalent as an identifier using a mixin then we statically check if the code that displays the variable will be compiled. If so then write the variable for real.

In D this doesn't makes much sense since everything in this function is prepared at compile-time.

New implementation...
< >
programming-idioms.org