overiding assignment in module

V

Viktor Marohnic

Hello.
I would to do something like this.

container = []

p1 = point()
l1 = line()

and i would like to override = method of the module so that its puts
all objects into container.
how i can do something like that.
thanks for help,
viktor.
 
F

Fredrik Lundh

Viktor said:
I would to do something like this.

container = []

p1 = point()
l1 = line()

and i would like to override = method of the module so that its puts
all objects into container.
how i can do something like that.

you cannot, at least not as you've described the problem. assignment is not
an operator in Python; it's a statement that modifies the current namespace.

things you can do include

- use an explicit target object

x.p1 = point()
x.l1 = line()

- execute the script in a controlled fashion, and inspect the resulting namespace:

myscript = """
p1 = point()
l1 = line()
"""

# create a new namespace, and add "built-in" functions to it
namespace = {}
namespace["point"] = point
namespace["line"] = line

# execute the script in this namespace
exec myscript in namespace

for key, item in namespace.iteritems():
...

</F>
 
S

Steven D'Aprano

Hello.
I would to do something like this.

container = []

p1 = point()
l1 = line()

Choosing names that look like numbers is terrible practice. Don't use l,
l1, O, ll, and so forth, unless you are trying to deliberately make your
code hard to read, hard to understand, and easy to miss bugs.

and i would like to override = method of the module so that its puts
all objects into container.

What do you mean by put all objects into container?

Do you mean:

container = []
container = point()
container = line()

Or do you mean:

container = []
container.append(point())
container.append(line())

Or even:

container = []
container.insert(0, point())
container.insert(0, line())

Or possibly even:

container = []
container.extend(point())
container.extend(line())


how i can do something like that.

Choose a different language.

There is no assignment method in Python.
 
V

Viktor Marohnic

Ok thanks a lot. I think i got the point.
I also thought that it could be possible to do something like this
globals().__setitem__ = custom_setter
but __setitem__ is readonly
 

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
474,269
Messages
2,571,338
Members
48,025
Latest member
Rigor4

Latest Threads

Top