How can I check if a Jython object implements a Java interface?
Example: Jython's dict is really PyDictionary which implements the Map interface. If I use isinstance(), it simply reports False:
>>> from java.util import Map
>>> from org.python.core import PyDictionary
>>> isinstance({}, Map)
False
>>> isinstance(PyDictionary(), Map)
False
You can check to see if an object implements an interface by using Class.isInstance() (an interface is an instance of Class):
>>> from java.util import Map
>>> from org.python.core import PyDictionary
>>> Map.isInstance({})
True
>>> Map.isInstance(PyDictionary())
True
Related
Below DataFrame of pandas is not validated by pydantic. How to handle this?
from pydantic.dataclasses import dataclass
#dataclass
class DataFrames:
dataframe1: pd.DataFrame = None
dataframe2: pd.DataFrame = None
This throws the following error:
File "pydantic\validators.py", line 715, in find_validators
RuntimeError: no validator found for <class 'pandas.core.frame.DataFrame'>, see `arbitrary_types_allowed` in Config
Personally, I'd mistyped the type annotation
class Foo(BaseModel):
bar = Optional[NonNegativeInt]
Rather than;
class Foo(BaseModel):
bar: Optional[NonNegativeInt]
Silly one ik, but double check that :)
According to the Pydantic Docs, you can solve your problems in several ways.
The simplest one is simply to allow arbitrary types in the model config, but this is functionality packaged with the BaseModel : quoting the docs again :
Keep in mind that pydantic.dataclasses.dataclass is a drop-in replacement for dataclasses.dataclass with validation, not a replacement for pydantic.BaseModel
With that in mind, the following code runs fine :
import pandas as pd
from pydantic import BaseModel
class DataFrames(BaseModel):
dataframe1: pd.DataFrame = None
dataframe2: pd.DataFrame = None
class Config:
arbitrary_types_allowed = True
If you came here with general problem no validator found for <class 'XYZ'> you should check missed BaseModel inheritance:
from pydantic import BaseModel
class MyCustomType: # We forgot inheritance here, should be MyCustomType(BaseModel)
id: int
text: str
class MyCustomClass2(BaseModel):
data: List[MyCustomType]
In the kotlin repl:
>>> import java.io.StringReader
>>> val json = p.parse(StringReader("""{"abc":"123"}""")) as JsonObject
>>> json.string("abc")
error: unresolved reference: string
json.string("abc")
^
>>> json
JsonObject(map={abc=123})
Get error unresolved reference. None of the examples here: https://github.com/cbeust/klaxon work
You need to import the string function as well, since it is an extension function, and it is not imported together with its receiver type Parser by default:
import com.beust.klaxon.string
json.string("abc")
When using edward, we always use from edward.models import Normal , but i didn't find the declaration of Normal in github
anybody who can tell me where is it
They are defined in edward/models/random_variables.py.
You import the Normal class like this:
from edward.models import Normal
This suggests looking in edward/models/__init__.py, which has this line:
from edward.models.random_variables import *
Looking in edward/models/random_variables.py we find this code:
from edward.models.random_variable import RandomVariable as _RandomVariable
from tensorflow.contrib import distributions as _distributions
# Automatically generate random variable classes from classes in
# tf.contrib.distributions.
_globals = globals()
for _name in sorted(dir(_distributions)):
_candidate = getattr(_distributions, _name)
if (_inspect.isclass(_candidate) and
_candidate != _distributions.Distribution and
issubclass(_candidate, _distributions.Distribution)):
# to use _candidate's docstring, must write a new __init__ method
def __init__(self, *args, **kwargs):
_RandomVariable.__init__(self, *args, **kwargs)
__init__.__doc__ = _candidate.__init__.__doc__
_params = {'__doc__': _candidate.__doc__,
'__init__': __init__}
_globals[_name] = type(_name, (_RandomVariable, _candidate), _params)
del _candidate
This goes through the tensorflow.contrib.distributions module looking for classes derived from tensorflow.contrib.distributions.Distribution (ignoring other attributes like e.g. the __file__ member of the module, or the base Distribution class itself). For each one, it does a bit of hacking (which only affects the generated documentation) then executes this key line:
_globals[_name] = type(_name, (_RandomVariable, _candidate), _params)
The type() built-in function creates a new type i.e. declares a new class. The second parameter is the list of base classes, which here is edward's RandomVariable class and the TensorFlow random variable class. Earlier it defined _globals to be globals(), which is a built-in function returning the dictionary of the module's variables. Therefore, in the case you're interested in, the line above is equivalent to the following:
from edward.models.random_variable import RandomVariable as EdRandVar
from tensorflow.contrib.distributions import Normal as TfNormal
Normal = type("Normal", (EdRandVar, TfNormal), {...})
Which in turn is equivalent to this (if you ignore the docstring stuff):
from edward.models.random_variable import RandomVariable as EdRandVar
from tensorflow.contrib.distributions import Normal as TfNormal
class Normal(EdRandVar, TfNormal):
pass
I'm trying to figure out how to use applyOptional. I've got this:
import monocle.function.all.index
import monocle.macros.{GenLens, Lenses}
import monocle.std.map._
import monocle.syntax.ApplyOptionalOps._
import monocle.function.Index._
val map: Map[Int, String] = Map.empty
val lens = map applyOptional index(4)
But the compiler tells me "Cannot resolve symbol applyOptional." I imported ApplyOptionalOps._ just to confirm that I had the right imports.
ApplyOptionalOps is the case class with the source object as the parameter, so by importing its companion object one can't access its functions. One should import monocle.syntax.apply._ instead, which extends ApplySyntax trait containing implicit conversion from generic source object to ApplyOptionalOps as well as some other operation wrappers. In fact, for just this example it the following imports is sufficient:
import monocle.syntax.apply._
import monocle.function.Index._
val map: Map[Int, String] = Map.empty
val lens = map applyOptional index(4)
I've looked through the Jython book on Jython.org and perused the Internet for some answers but I don't see anywhere that suggests the following (of what seems to me to be strange) behavior. I'm doing this using PyDev 1.5.7 in Eclipse 3.6.1 with Jython 2.5.3.
Does a Jython class that inherits from a Java interface with setters automatically call the setVal when self.val = val is executed?
Here's the Java interface:
package com.me.mypackage
import org.python.core.PyDictionary;
public interface MyInterface {
public double getMaxBW();
public boolean setMaxBW(double bw);
}
Here's the Jython class:
from com.me.mypackage import MyInterface
class MyClass(MyInterface):
def __init__(self, maxBW):
self.maxBW = maxBW
def setMaxBW(self, maxBW):
self.maxBW = maxBW
def getMaxBW(self):
return self.maxBW
When I instantiate the class, in the __init__ function:
setMaxBW gets called when self.maxBW = maxBW is run
This function call in turn runs self.maxBW = maxBW
This code again calls setMaxBW
This function call in turn runs self.maxBW = maxBW
Repeat forever
As a result of this infinite recursion, I get a RuntimeError after the maximum recursion depth has been reached.
One thought was that this was something nifty new-style Python classes were doing (I've spent most of my Python time with old-style classes) but this problem doesn't occur with pure Jython (in Eclipse or standalone from the command line) that doesn't inherit from the Java interface. I haven't tried the interface inheritance outside of Eclipse.
And now I reiterate my initial question but in the context of my code: Is a Jython class that inherits a Java interface with setters automatically call setMaxBW when self.maxBW = maxBW is executed?