Function Repository Resource:

ObjectIfExists

Source Notebook

Get an object only if it exists

Contributed by: Bob Sandheinrich

ResourceFunction["ObjectIfExists"][obj,def]

gives obj if it exists and def otherwise.

Details and Options

If a default is not provided, a Missing["ObjectDoesNotExist", obj] value is used.
ResourceFunction["ObjectIfExists"] supports the same object types as the resource function ObjectExistsQ.

Examples

Basic Examples (2) 

Check if a given file exists:

In[1]:=
ResourceFunction["ObjectIfExists"][File["does/not/exist"]]
Out[1]=

Verify a file exists:

In[2]:=
Put[1, "does-exist"];
ResourceFunction["ObjectIfExists"][File["does-exist"], CreateFile[]]
Out[3]=

When a file does not exist, create one:

In[4]:=
ResourceFunction["ObjectIfExists"][File["does/not/exist"], File@CreateFile[]]
Out[4]=

Scope (1) 

Add to a databin if it exists, otherwise create a new one:

In[5]:=
DatabinAdd[
 ResourceFunction["ObjectIfExists"][Databin["No"], CreateDatabin[]], <|
  "FavoriteResourceFunctions" -> {"Bob", "Wiggled", "Birdsay"}|>]
Out[5]=

Applications (2) 

Deploy an API with a permissions group if one already exists:

In[6]:=
users = ResourceFunction["ObjectIfExists"][
  PermissionsGroup["APIUsers"], {"documentation@wolfram.com"}]
Out[6]=
In[7]:=
CloudDeploy[
 APIFunction[{"int" -> Integer}, ListPlot[Prime /@ Range[#int]] &, "PNG"], Permissions -> {users -> "Execute"}]
Out[7]=

Create a list of object references for objects that do not exist:

In[8]:=
objects = CloudObject /@ {"logs/log1", "logs/log2", "logs/log3", "logs/log4", "logs/log5"}
Out[8]=

Create only one of the object references:

In[9]:=
CloudPut["Found it!", RandomChoice[objects]]
Out[9]=

Create a tool that finds the first existent object on the list:

In[10]:=
searchObjects[objs_, i_] := ResourceFunction["ObjectIfExists"][Echo[objs[[i]], "checking:"], searchObjects[objs, i + 1]]
In[11]:=
Get@searchObjects[objects, 1]
Out[11]=

Properties and Relations (2) 

When an object does not exist and no default is given, Missing is used.:

In[12]:=
ResourceFunction["ObjectIfExists"][CloudObject["does/not/exist"]]
Out[12]=

The default does not evaluate until it is needed:

In[13]:=
ResourceFunction["ObjectIfExists"][File[$InstallationDirectory], Print[ ResourceFunction["BirdSay"][
   "SQUAWK!!!\nNo File"]]; "\[UpArrow]"]
Out[18]=

In this case it evaluates:

In[19]:=
ResourceFunction["ObjectIfExists"][File["does/not/exist"], Print[ ResourceFunction["BirdSay"][
   "SQUAWK!!!\nNo File"]]; "\[UpArrow]"]
Out[19]=

Version History

  • 1.0.0 – 02 June 2020

Related Resources

License Information