For example:
from fastapi import FastAPI, Depends
app = FastAPI()
def thing(x: int) -> str:
return f"x is : {x}"
#app.get("/")
async def root(x: int = Depends(thing)):
return {"message": x.upper()}
Here the input might be an integer, but the Depends(thing) is going to convert it to a string instead.
When running mypy on this code the following error is returned :
error: "int" has no attribute "upper" [attr-defined]
It seems as though the type-hints necessary are present, but I'm not sure how to use them in this case.
I wondered if there was something 'clever' that could be done with thing.__annotations__['return'], but I'm not really clever enough to know what.
Related
I'm trying to write a method that does something like this
Mono<A> ma = networkCall(); //this might fail
Mono<Void> mv = ma.map( a -> ....) #some logic to perform with `A`
return mv;
The trick is, ma might very well fail and then I would want to just log the situation and return a Mono<Void> that completes with no error.
Looking at the Mono api I just found onErrorResume or onErrorReturn but both would take a function that returns an A (which I can't fabricate), while I would like to return a Void.
I would imagine the solution is quite simple, but couldn't quite find the right operations for this.
So, what operations should I apply to ma to transform it into a Mono<Void> in case of error?
I just found onErrorResume or onErrorReturn but both would take a function that returns an A
onErrorReturn() indeed requires you to return an A, but onErrorResume() just requires you to return a Mono<A>, which can be empty.
So you can use:
doOnNext() to perform your logic with A if the call is successful;
doOnError() to log your error if the call is not successful;
onErrorResume() to return an empty result
then() to convert the result into a Mono<Void>.
Something like:
networkCall()
.doOnNext(a -> doSomethingWith(a))
.doOnError(e -> e.printStackTrace())
.onErrorResume(e -> Mono.empty())
.then();
I have the following case, a request is sent to my server, and I am parsing some GET parameters, in order to process it properly. After request is parsed, I am getting something like:
some_function(parameter1, parameter2, ...) ->
some_steps_here.
The idea is that I want to be able to return nice error codes if some of these parameters are missing. E.g. if user did not enter parameter1 into his url, I want to return the error instead of doing some_steps_here.
Was trying to solve it using pattern matching, but don't have idea how to do it at all.
First, if you write param1 and param2 as lower letters, it means an atom and not a Parameter. You want your function to be:
some_function(Param1, Param2, ...)
Regarding your question, I'd suggest to use function clauses to catch a case where Param1 == undefined for example
some_function(undefined, _Param2, ...) ->
io:format("Param1 is undefined~n");
some_function(_Param1, undefined, ...) ->
io:format("Param2 is undefined~n");
some_function(Param1, Param2, ...) ->
io:format("Params are OK!~n").
Every clause is separated by a ; and the last clause is terminated by a dot ..
Update:
Answering the comment below: Is there a way to make it more generic?
It really depends on your implementation. You need to think what is your desired input and if you don't get the desired input, what will you get? A specific atom? Just a random atom instead of a list? Below I've added some other options you might also use. And please, take a look at Learn You Some Erlang you will probably find all your answers there.
You can use guards to check for a specific type:
some_function(Param1, ...) when is_atom(Param1) ->
...
some_function(Param1, ...) -> ...
Or, case .. of to check for something specific:
some_function(Param1, Param2, ...) ->
case Param1=:=7 andalso is_list(Param2) of
true -> something;
false -> something_else
end.
Please see this and this for more information and examples.
To lone travelers stumbling upon this: see comments for the answer.
...
Writing a Java wrapper for a native library. A device generates data samples and stores them as structs. Two native ways of accessing them: either you request one with a getSample(&sampleStruct) or you set a callback function. Now, here is what does work:
The polling method does fill the JNA Structure
The callback function is called after being set
In fact, I am currently getting the sample right from the callback function
The problem: trying to do anything with the callback argument, which should be a struct, causes an "invalid memory access". Declaring the argument as the Structure does this, so I declared it as a Pointer. Trying a Pointer.getInt(0) causes invalid memory access. So then I declared the argument as an int, and an int is delivered; in fact, it looks very much like the first field of the struct I am trying to get! So does it mean that the struct was at that address but disappeared before Java had time to access it?
This is what I am doing now:
public class SampleCallback implements Callback{
SampleStruct sample;
public int callback(Pointer refToSample) throws IOException{
lib.INSTANCE.GetSample(sample); // works no problem
adapter.handleSample(sample);
return 1;
} ...
But neither of these does:
public int callback(SampleStruct sample) throws IOException{
adapter.handleSample(sample);
return 1;
}
...
public int callback(Pointer refToSample) throws IOException{
SampleStruct sample = new SampleStruct();
sample.timestamp = refToSample.getInt(0);
...
adapter.handleSample(sample);
return 1;
}
Also, this does in fact deliver the timestamp,
public int callback(int timestamp) throws IOException{
System.out.println("It is " + timestamp + "o'clock");
return 1;
}
but I would really prefer the whole struct.
This is clearly not going to be a popular topic and I do have a working solution, so the description is not exactly full. Will copy anything else that might be helpful if requested. Gratitude prematurely extended.
For Testing purposes I'm trying to design a way to verify that the results of statistical tests are identical across versions, platforms and such. There are a lot things that go on that include ints, nums, dates, Strings and more inside our collections of Objects.
In the end I want to 'know' that the whole set of instantiated objects sum to the same value (by just doing something like adding the checkSum of all internal properties).
I can write low level code for each internal value to return a checkSum but I was thinking that perhaps something like this already exists.
Thanks!
_swarmii
This sounds like you should be using the serialization library (install via Pub).
Here's a simple example to get you started:
import 'dart:io';
import 'package:serialization/serialization.dart';
class Address {
String street;
int number;
}
main() {
var address = new Address()
..number = 5
..street = 'Luumut';
var serialization = new Serialization()
..addRuleFor(address);
Map output = serialization.write(address, new SimpleJsonFormat());
print(output);
}
Then depending on what you want to do exactly, I'm sure you can fine tune the code for your purpose.
Updated below...
I recently started experimenting with ServiceStack in F#, so naturally I started with porting the Hello World sample:
open ServiceStack.ServiceHost
open ServiceStack.ServiceInterface
open ServiceStack.WebHost.Endpoints
[<CLIMutable; Route("/hello"); Route("/hello/{Name}")>]
type Hello = { Name : string }
[<CLIMutable>]
type HelloResponse = { Result : string }
type HelloService() =
inherit Service()
member x.Any(req:Hello) =
box { Result = sprintf "Hello, %s!" req.Name }
type HelloAppHost() =
inherit AppHostBase("Hello Web Services", typeof<HelloService>.Assembly)
override x.Configure container = ()
type Global() =
inherit System.Web.HttpApplication()
member x.Application_Start() =
let appHost = new HelloAppHost()
appHost.Init()
That works great. It's very concise, easy to work with, I love it. However, I noticed that the routes defined in the sample allow for the Name parameter to not be included. Of course, Hello, ! looks kind of lame as output. I could use String.IsNullOrEmpty, but it is idiomatic in F# to be explicit about things that are optional by using the Option type. So I modified my Hello type accordingly to see what would happen:
[<CLIMutable; Route("/hello"); Route("/hello/{Name}")>]
type Hello = { Name : string option }
As soon as I did this, the F# type system forced me to deal with the fact that Name might not have a value, so I changed HelloService to this to get everything to compile:
type HelloService() =
inherit Service()
member x.Any(req:Hello) =
box { Result =
match req.Name with
| Some name -> sprintf "Hello, %s!" name
| None -> "Hello!" }
This compiles, and runs perfectly when I don't supply a Name parameter. However, when I do supply a name...
KeyValueDataContractDeserializer: Error converting to type: Type
definitions should start with a '{', expecting serialized type
'FSharpOption`1', got string starting with: World
This wasn't a complete surprise of course, but it brings me to my question:
It would be trivial for me to write a function that can wrap an instance of type T into an instance of type FSharpOption<T>. Are there any hooks in ServiceStack that would let me provide such a function for use during deserialization? I looked, but I couldn't find any, and I'm hoping I was just looking in the wrong place.
This is more important for F# use than it might seem at first, because classes defined in F# are by default not allowed to be null. So the only (satisfying, non-hacky) way of having one class as an optional property of another class is with, you guessed it, the Option type.
Update:
I was able to sort-of get this working by making the following changes:
In the ServiceStack source, I made this type public:
ServiceStack.Text.Common.ParseFactoryDelegate
...and I also made this field public:
ServiceStack.Text.Jsv.JsvReader.ParseFnCache
With those two things public, I was able to write this code in F# to modify the ParseFnCache dictionary. I had to run this code prior to creating an instance of my AppHost - it didn't work if I ran it inside the AppHost's Configure method.
JsvReader.ParseFnCache.[typeof<Option<string>>] <-
ParseFactoryDelegate(fun () ->
ParseStringDelegate(fun s -> (if String.IsNullOrEmpty s then None else Some s) |> box))
This works for my original test case, but aside from the fact that I had to make brittle changes to the internals of ServiceStack, it sucks because I have to do it once for each type I want to be able to wrap in an Option<T>.
What would be better is if I could do this in a generic way. In C# terms, it would be awesome if I could provide to ServiceStack a Func<T, Option<T>> and ServiceStack would, when deserializing a property whose generic type definition matches that of the return type of my function, deserialize T and then pass the result into my function.
Something like that would be amazingly convenient, but I could live with the once-per-wrapped-type approach if it were actually part of ServiceStack and not my ugly hack that probably breaks something somewhere else.
So there are a couple of extensibility points in ServiceStack, on the framework level you can add your own Custom Request Binder this allows you to provide your own model binder that's used, e.g:
base.RequestBinders.Add(typeof(Hello), httpReq => {
var requestDto = ...;
return requestDto;
});
But then you would need to handle the model binding for the different Content-Types yourself, see CreateContentTypeRequest for how ServiceStack does it.
Then there are hooks at the JSON Serializer level, e.g:
JsConfig<Hello>.OnDeserializedFn = dto => newDto;
This lets you modify the instance of the type returned, but it still needs to be the same type but it looks like the F# option modifier changes the structural definition of the type?
But I'm open to adding any hooks that would make ServiceStack more palatable for F#.
What does the code look like to generically convert a normal Hello type to an F# Hello type with option?
The only thing I can think of is to replace the option type with your own type, one that has an implicit conversion from string to myOption, and anything else you need.
Not all that nice, but workable. Your type would probably also need to be serializable.
type myOption =
| None
| Some of string
static member public op_Implicit (s:string) = if s <> null then Some s else None
member public this.Value = match this with
| Some s -> s
| _ -> null
member this.Opt = match this with
| Some s -> Option.Some s
| None -> Option.None
Your record type would then be
[<CLIMutable>]
type Hello =
{ Name : myOption }
On the other hand, ServiceStack is open source, so maybe something could be done there.