Is it possible to override the assignment ('=') operator in Python?
It is not possible to override the implementation of x = y
. See Facts and Myths about Python Names and Values for details of what assignment means.
You can override x.a = y
, with __setattr__
, it is (roughly) x.__setattr__('a', y)
.
You can override x[k] = y
with __setitem__
, it is (roughly) x.__setitem__(k, y)
.
But you can't override x = y
.
How to Emulate Assignment Operator Overloading in Python?
I ended up creating a Model metaclass called ModelMeta that registers the typed attributes.
See http://github.com/espeed/bulbs/blob/master/bulbs/model.py
In this case, the typed attributes are graph-database "properties", which are all subclasses of the Property class.
See https://github.com/espeed/bulbs/blob/master/bulbs/property.py
Here's an example Model declaration:
# people.py
from bulbs.model import Node, Relationship
from bulbs.property import String, Integer, DateTime
from bulbs.utils import current_datetime
class Person(Node):
element_type = "person"
name = String(nullable=False)
age = Integer()
class Knows(Relationship):
label = "knows"
created = DateTime(default=current_datetime, nullable=False)
Example usage:
>>> from people import Person
>>> from bulbs.neo4jserver import Graph
>>> g = Graph()
# Add a "people" proxy to the Graph object for the Person model:
>>> g.add_proxy("people", Person)
# Use it to create a Person node, which also saves it in the database:
>>> james = g.people.create(name="James")
>>> james.eid
3
>>> james.name
'James'
# Get the node (again) from the database by its element ID:
>>> james = g.people.get(james.eid)
# Update the node and save it in the database:
>>> james.age = 34
>>> james.save()
# Lookup people using the Person model's primary index:
>>> nodes = g.people.index.lookup(name="James")
See...
- Bulbs Model API: http://bulbflow.com/docs/api/bulbs/model/
- Bulbs Model Quickstart: http://bulbflow.com/quickstart/#models
Assignment operator overloading in python Abstract Syntax Trees
You do not need to use astunparse
, the ast
module includes an unparse
method:
import ast
class AssignOverload(ast.NodeTransformer):
def visit_Assign(self, node):
return ast.Call(func=ast.Name(id='copy_variable_value'),
args=[ast.Constant(value=ast.unparse(i)) for i in [*node.targets, node.value]],
keywords=[])
code_chunk = "town_slot=cxt.my_town"
a = AssignOverload()
result = a.visit(ast.parse(code_chunk))
print(ast.unparse(result))
Output:
copy_variable_value('town_slot', 'cxt.my_town')
overloading augmented arithmetic assignments in python
You need to add return self
to your method. Explanation:
The semantics of a += b
, when type(a)
has a special method __iadd__
, are defined to be:
a = a.__iadd__(b)
so if __iadd__
returns something different than self
, that's what will be bound to name a
after the operation. By missing a return
statement, the method you posted is equivalent to one with return None
.
Python: overloading tuple multi-assignment capabilities?
Yes. Implement __iter__()
.
class unpackable_dict(dict):
def __iter__(self):
return (self[key] for key in sorted(self.keys()))
d = unpackable_dict(a=1, b=2)
a, b = d
The reason you normally can't unpack values from a dict like you can a tuple is that dicts don't have a defined order. I've used a generator expression to get the items out in the sorted order of their keys. You might consider using an OrderedDict
instead, though.
How can I overload the assignment of a class member?
Can't you use properties and override setter for the field?
Citing from django documentation:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def _get_full_name(self):
return "%s %s" % (self.first_name, self.last_name)
def _set_full_name(self, combined_name):
self.first_name, self.last_name = combined_name.split(' ', 1)
full_name = property(_get_full_name)
full_name_2 = property(_get_full_name, _set_full_name)
Related Topics
Setting Different Color for Each Series in Scatter Plot on Matplotlib
Creating a New Column Based on If-Elif-Else Condition
Choosing a File in Python with Simple Dialog
Python 3: Importerror "No Module Named Setuptools"
Execute Multiple Commands in Paramiko So That Commands Are Affected by Their Predecessors
Making the Background Move Sideways in Pygame
Python Process Pool Non-Daemonic
How to Remove All Characters After a Specific Character in Python
How to Manually Create a Legend
Extracting Date from a String in Python
How to Extract All the Emojis from Text
Reconstruct a Categorical Variable from Dummies in Pandas
Automatically Import Modules When Entering the Python or Ipython Interpreter
Seaborn Is Not Plotting Within Defined Subplots
What Are the Most Common Python Docstring Formats
Pandas Dataframe Stored List as String: How to Convert Back to List