Replies: 5 comments 3 replies
-
As an experiment, I just wrote up a |
Beta Was this translation helpful? Give feedback.
-
Thank you for such outstanding engagement and support. It is uncommon. This is very interesting. However, I'm going to have to study how I do have a concern which might be unwarranted. At the CPython REPL:
|
Beta Was this translation helpful? Give feedback.
-
A relatively terse explanation:
This is a sharp corner of python involving class-vs-instance attributes, as well as mutable vs immutable objects. Here's a demo/explanation: class Foo:
int_a = 1
mutable = []
def __init__(self, int_b):
self.int_b = int_b
foo = Foo(2)
# First, lets demo `int_a`; these all point to the exact same object.
print(foo.int_a) # 1; `int_a` doesn't exist in the `foo` **instance**, so it looks it up in the `Foo` **class**
# The following 3 prints are different ways of saying the **exact same thing**
print(Foo.int_a) # 1
print(foo.__class__.int_a) # 1
print(type(foo).int_a) # 1
print()
# Now, lets set the instance `foo`'s int_a
foo.int_a = 100
print(foo.int_a) # 100
print(foo.__class__.int_a) # 1
# When we set `foo.int_a`, it wrote the value *just for that instance*.
# Now when we do the `foo.int_a` lookup, it's looking at it's own `int_a`, **not the classes**
print()
# But now lets see what happens when we modify a mutable object, such as a list:
foo.mutable.append("I added this string to the instance!")
print(foo.mutable) # ['I added this string to the instance!']
print(Foo.mutable) # ['I added this string to the instance!']
# when we did get `foo.mutable`, that attribute doesn't exist in the `foo` instance,
# but it does exist in the `Foo` **class**, so we got the list from `Foo.mutable`.
# Then, we did the `append` operation, which adds an element to that list (it's mutable).
# This means that, unless directly overwritten at the instance-level, all objects of Foo
# will share the same `mutable` list. |
Beta Was this translation helpful? Give feedback.
-
Many thanks! I have learned a lot from you. The |
Beta Was this translation helpful? Give feedback.
-
A couple observations from my testing:
I'll keep testing. |
Beta Was this translation helpful? Give feedback.
-
I have a class in uPython that I want to interact with in CPython.
self.obj
is the belay device. Rather than issuing commands likeself.obj('klass.attr')
to get the value of the attr, I'd rather typeklass.attr
in CPython and have it proxy for me. Rather thanself.obj('klass.__dict__')
orself.obj('klass.__class__.__dict__')
, I prefer to type something likeklass.get()
which makes the call for me to get all the attrs of the uPython object. On CPython, my__getattr__
method looks like this.This works. But when I try to implement a
__setattr__
method, I get the typical recursive errors issues.Has anyone tried something like this? What method(s) did you use to successfully proxy a class in C for a uPy class?
Beta Was this translation helpful? Give feedback.
All reactions