How to detect if current scope has a parent in CMake?

I think the most robust approach is to use the PARENT_DIRECTORY directory property.

This will yield the correct answer regardless of whether it's called before or after the project command, and regardless of whether the parent and child both have the same project name.

get_directory_property(hasParent PARENT_DIRECTORY)
if(hasParent)
  message(STATUS "Has a parent scope.")
else()
  message(STATUS "Doesn't have a parent scope.")
endif()

CMake version 3.21 added the PROJECT_IS_TOP_LEVEL global variable for this:

A boolean variable indicating whether the most recently called project() command in the current scope or above was in the top level CMakeLists.txt file.

project(my_project)
[...]

if(PROJECT_IS_TOP_LEVEL)
  message(STATUS "Is a top-level project.")
endif()