How to use a certain set of values for typing in Python - python-typing

I need to specify a certain set of values as the expected return type for my function. Let's say there was defined some class called Scene which has attribute name which is supposed to be a string which may end only with "1K", "2K" or "4K". Now I want to write a function which takes this class as an argument and returns the last 2 characters of its name as a string. Is there a way to specify this function return type like a set of exact string values using built-in modules in Python 3.7.7? Something like this:
def scene_resolution(sc : Scene): -> any value in {'1K', '2K', '4K'}: # return type?
res = sc.name[-2:]
assert res in {'1K', '2K', '4K'}
return res
I know about using Literal from typing_extensions, but unfortunately it works only with Python 3.8 and higher, and the API of the soft I'm dealing with uses Python 3.7.7. I've also tried to make something with enum.Enum but could not make it work properly.
Do you have any suggestions?
UPD. The only way I found so far is to define some function that returns the set I need and use its name as expected return type. Not sure whether it is correct way and a good practice, but at least it works.

Related

Is it possible to use only one of the return values when initializing members in Go?

I understand how to use multiple return values in go. I further understand that in most cases one of the returns is an error, so ignoring returned values can be dangerous.
Is there a way to ignore a value in struct initializer like this? The below example does not work as Split returns two values, but I am interested only in the first one. I can of course create a variable but...
someFile := "test/filename.ext"
contrivedStruct := []struct{
parentDir string
}{
{ parentDir: filepath.Split(someFile) },
}
It's not possible to use only one of the return values when initializing members in Go.
Using variables clearly expresses your intent.
Go sometimes feels like it could be more succinct, but the Go authors favoured readability over brevity.
Alternatively, use a wrapper function. There are several 'Must' wrapper functions in the standard library, like: template.Must.
func first(args ...string) string {
return args[0]
}
For your particular example, splitting paths, see filepath.Base or filepath.Dir.
No, there is no way to skip one of the returned values in structure initializer.

Returning multiple values from a method

I have a method drive that goes like this:
public double drive(double milesTraveled, double gasUsed)
{
gasInTank -= gasUsed;
return totalMiles += milesTraveled;
}
I know I can't return multiple values from a method, but that's kind of what I need to do because I need both of these values in my main method, and as it is now it's obviously only returning the one. I can't think of anything that would work. Sorry if this is a super beginner question. What can I do to get both values to return from the method?
You can return multiple value from a function. To do this You can use structure.
In the structure you can keep required field and can return structure variable after operation.
You can also make a class for the required field if You are using OOPS supporting language but Structure is best way.
In most languages you can only return a single value from a method. That single value could be a complex type, such as a struct, array or object.
Some languages also allow you to define output parameters or pass in pointers or references to outside storage locations. These kinds of parameters also allow you to return additional values from your method.
not sure, but can you take array of your values?
array[0]=gasInTank;
array[0] -= gasUsed;
array[1]=milesTraveled;
array[1] -= milesTraveled;
return array;

Why/How to use passed constants in function?

I've seen classes where constants are passed to methods, I guess its done to define some kind of setting in that function. I cant find it anywhere now to try to find out the logic, so I though I could ask here. How and why do you use this concept and where can I find more information about it?
The example below is written in PHP, but any language that handles constants would do I guess..
// Declaring class
class ExampleClass{
const EXAMPLE_CONST_1 = 0;
const EXAMPLE_CONST_2 = 1;
function example_method($constant(?)){
if($constant == ExampleClass::EXAMPLE_CONST_1)
// do this
else if($constant == ExampleClass::EXAMPLE_CONST_2)
// do that
}
}
// Using class
$inst = new ExampleClass();
$inst->example_method(ExampleClass::EXAMPLE_CONST_1);
To me its more clear to pass "ExampleClass::EXAMPLE_CONST_1" than to just pass "1", but it's that the only reason to pass constant?
Simply passing 1 doesn't say much. By having a constant you can have a description about the settings in the name.
example:
constant RAIN = 1;
method setWeather(RAIN);
Atleast that's how and why I use it.
It is always a good idea to avoid literals being passed around. By assigning a name, anyone reading your code has a chance to understand what that value means - a number has no meaning. It might also help you maintaining your code: If for some requirement the value has to be changed, you can easily do it in one place, instead of checking each and every value occurrence.

How can I get a function's name by its pointer in Lua?

In Lua I've created a pretty printer for my tables/objects. However, when a function is displayed, it's shown as a pointer.
I've been reading up on Lua Introspection but when I introspect the function with debug.getinfo() it won't return the function's name. This seems to be due to a scoping issue but I'm not sure how to get around it.
What is the best way to get a function's name using its pointer? (I understand functions are first class citizens in Lua and that they can be created anonymously, that's fine)
when you create the functions, register them in a table, using them as keys.
local tableNames = {}
function registerFunction(f, name)
tableNames[f] = name
end
function getFunctionName(f)
return tableNames[f]
end
...
function foo()
..
end
registerFunction(foo, "foo")
...
getFunctionName(foo) -- will return "foo"
For some reason, it seems to work only with number parameters (that is, active functions on the stack).
The script
function a() return debug.getinfo(1,'n') end
function prettyinfo(info)
for k,v in pairs(info) do print(k,v) end
end
prettyinfo(a())
prints
name a
namewhat global
but if I change the last line to
prettyinfo(debug.getinfo(a, 'n'))
it gives me only an empty string:
namewhat

Defining Lua methods as initialization

In the Lua language, I am able to define functions in a table with something such as
table = { myfunction = function(x) return x end }
I wondered if I can created methods this way, instead of having to do it like
function table:mymethod() ... end
I am fairly sure it is possible to add methods this way, but I am unsure of the proper name of this technique, and I cannot find it looking for "lua" and "methods" or such.
My intention is to pass a table to a function such as myfunction({data= stuff, name = returnedName, ?method?init() = stuff}).
Unfortunately I have tried several combinations with the colon method declaration but none of them is valid syntax.
So...anyone here happens to know?
Sure: table:method() is just syntactic sugar for table.method(self), but you have to take care of the self argument. If you do
tab={f=function(x)return x end }
then tab:f(x) won't work, as this actually is tab.f(tab,x) and thus will return tab instead of x.
You might take a look on the lua users wiki on object orientation or PiL chapter 16.

Resources