Replace all references to one object with references to other

J

Jack Bates

I have two objects, and I want to replace all references to the first
object - everywhere - with references to the second object. What can I
try?
 
J

John Gordon

In said:
I have two objects, and I want to replace all references to the first
object - everywhere - with references to the second object. What can I
try?

The simplest answer to your question is to assign object2 to object1
at the very beginning of your code, but that is a very naive solution
and can easily fail based on lots of factors.

What's your context: A single source file? Many source files? A live
application with persistent data?

What are your two objects? Do they provide an identical interface?
 
J

John Gordon

The simplest answer to your question is to assign object2 to object1

I think I have that backwards, but the intent should be clear:

object1 = object2

# many references to object1 follow, which will now reference object2
 
S

Steven D'Aprano

Jack said:
I have two objects, and I want to replace all references to the first
object - everywhere - with references to the second object. What can I
try?

Another way of solving your *actual* problem.

"Replace all references to object1 with object2 instead" is a means to an
end, not the end itself. What are you trying to solve? Focus on *that*
problem, not your supposed solution, because "replace all..." is doomed to
fail.

There is no "master list" of objects available to you. All you have is one
or more namespaces containing objects. Many of those objects themselves
will contain other objects, and so on. All you can do is walk through each
namespace in turn, recursively into each object, searching for the object
you want to replace. But that may not help you, because there's no
guarantee that having found it you can replace it safely, *or at all*.

While Python does allow code to reach deeply into the internals of a wide
range of objects -- very little is truly private in Python -- do you
*really* want to be taking responsibility for safely replacing objects from
within arbitrary other objects? If so, Python gives you the tools to shoot
yourself in the foot, although it won't necessarily be easy, or pretty, or
fast.

So, tell us what your real problem is, the end towards which you
think "replace all..." is the solution, and we'll see if we can help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top