It seems pretty common to me to have an argument, in a dynamically typed language that is either an Object or a key to lookup that object. For instance when I’m working with a database I might have a method getMyRelatedStuff(person)
All I really need to lookup the related stuff is the id of the person so my method could look like this in python:
def getMyRelatedStuff(person_or_id):
id = person_or_id.id if isinstance(person,User) else person_or_id
#do some lookup
Or going the other direction:
def someFileStuff(file_or_name):
file = file_or_name if hasattr(file,'write') else open(file_or_name)
EDIT: I am looking for a built in syntax for this, the closest I can think of is implicit and explicit keywords in C# that allow you to define a cast between types.
I study programming languages for a living. I’ve never seen a language with a built-in syntax for that operation. I’m not even sure what you want such a syntax to look like, especially since you can define a function for any of these patterns.
People who like extensible syntax tend to define Lisp macros 🙂