What I’m trying to do:
Check if an object is a ProxyObject so that I can convert it to a dictionary.
What I’ve tried and what’s not working:
Checking an object with type
function and with isinstance
with Proxy as the check for both, but in both cases I get that Proxy isn’t defined.
Code Sample:
# What doesn't work
type(variable) == Proxy
type(variable) == ProxyObject
isinstance(variable, Proxy)
isinstance(variable, ProxyObject
# My hacky workaround
str(type(variable)) == "<class 'Proxy'>"
This is for Javascript proxy objects, right? I don’t have an answer for you, but I’m curious about how you get to the point of not knowing that the object came from Javascript? At some point you make a Javascript call (or import from anvil.js) to get the object in the first place. Could you do the conversion at that point, so you’re presenting dicts to Python from the start?
Python has an EAFP convention - it’s Easier to Ask for Forgiveness than Permission. (the opposite convention is LBYL - Look Before You Leap).
If you Google those terms, you’ll find plenty to read.
In this case, that means don’t bother trying to work out the type at all. Instead, use a try/except block - try what you expect to be the usual case, catch the exception that happens when it’s the opposite and handle that in the except clause.
1 Like
Yeah, for JS objects. So the thing is, I absolutely know that it’s coming from outside of Anvil/python, but the object I’m getting, is a huge proxy object with some proxy objects as values that I parse out. To parse, I’m looping over the larger proxy object’s keys/values and then unpacking any proxy object values I get so that it can be worked with more nicely. I also know which fields will be proxy objects, but I’m trying to make my code extensible so I don’t have to explicitly tell the parsing code which keys need to be unpacked.
Hmm, never heard of those coding terms before, I’ll have to do some reading when I get a chance. Thanks!
1 Like
The easiest way to get the Proxy type is to get something you know is definitely a Proxy object and ask for its type.
from anvil.js.window import document
JsProxyType = type(document)
It’s not uncommon that an object’s class doesn’t exist in the namespace.
Python has a whole module dedicated to exposing types that can’t be easily accessed otherwise.
It’s called types
. It has code like:
class A:
def c(): pass
MethodType = type(A().c)
and you would use it like
from types import MethodType
4 Likes
As always, you come in with some technical corner of python and/or programming I didn’t even know I didn’t know!
1 Like