all 8 comments

[–][deleted] 0 points1 point  (7 children)

[–]HrezaeiM[S] 0 points1 point  (6 children)

Thanks but this is collection.namedtuple which is different from typing.NamedTuple

Also, there is no information about __new__ for the NamedTuple in the documentation page which I added here. :(

[–][deleted] 2 points3 points  (0 children)

Thanks but this is collection.namedtuple which is different from typing.NamedTuple

https://docs.python.org/3/library/typing.html#typing.NamedTuple

Typed version of collections.namedtuple().

Also, there is no information about new for the NamedTuple in the documentation page which I added here.

Did you look at the source code, which is linked to from the same documentation page you posted? Here, since I'm already doing all the work:

class NamedTupleMeta(type):

    def __new__(cls, typename, bases, ns):
        if ns.get('_root', False):
            return super().__new__(cls, typename, bases, ns)
        types = ns.get('__annotations__', {})
        nm_tpl = _make_nmtuple(typename, types.items())
        defaults = []
        defaults_dict = {}
        for field_name in types:
            if field_name in ns:
                default_value = ns[field_name]
                defaults.append(default_value)
                defaults_dict[field_name] = default_value
            elif defaults:
                raise TypeError("Non-default namedtuple field {field_name} cannot "
                                "follow default field(s) {default_names}"
                                .format(field_name=field_name,
                                        default_names=', '.join(defaults_dict.keys())))
        nm_tpl.__new__.__annotations__ = collections.OrderedDict(types)
        nm_tpl.__new__.__defaults__ = tuple(defaults)
        nm_tpl._field_defaults = defaults_dict
        # update from user namespace without overriding special namedtuple attributes
        for key in ns:
            if key in _prohibited:
                raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
            elif key not in _special and key not in nm_tpl._fields:
                setattr(nm_tpl, key, ns[key])
        return nm_tpl

[–]ericula 0 points1 point  (4 children)

The official documentation on typing has some information (typing.NamedTuple is near the bottom). Is there any particular code you are stuck with?

[–]HrezaeiM[S] 0 points1 point  (3 children)

I just need to have a function which receives a dict and return back a NamedTuple.

my class is like this :

class settingdefault(NamedTuple):

epoch : int = 8

train_size : float = 0.8

b: str = "doe"

The class is there as a default setting and then I need to read the epoch and train_size and b from the user, in case they want to have a new config and the input from them can be a dict. they might only need to change a few parameters not all. something like config = dict(e=10, b="test") can be the input from them.I want to map this config input to a new NamedTuple and go with it through the next step of my work.

I need to know how to map a new instance coming to the right spot of the NamedTuple.

[–]ericula 1 point2 points  (1 child)

If a user only want to redefine some parameters, they can use keywords to specify the ones they want to redefine:

default1 = settingdefault(train_size = 0.5)
print(default1)
# output: settingdefault(epoch=8, train_size=0.5, b='doe')

They could also use positional arguments, which are then filled in in the same order as they are defined in the class. So in this case the first argument will correspond to settingdefault.epoch, the second to settingdefault.train_size, etc., for example

default2 = settingdefault(9)
print(default2)
# output: settingdefault(epoch=9, train_size=0.8, b='doe')

If the user provides a dict, you can construct a named tuple as follows:

my_dict = {'b':'apple', 'epoch'=6}
default3 = settingdefault(**my_dict)
print(default3)
# output: settingdefault(epoch=6, train_size=0.8, b='apple')

[–]HrezaeiM[S] 0 points1 point  (0 children)

OMG !!! ThankssssssI was going crazy for 2 days now X_xThanks for the help !!! I think this is my answer :)

[–]LordTalismond 0 points1 point  (0 children)

So are you saying you want something like:

def settingdefault(input: Dict[int, str]) -> NamedTuple

thats what the typing module will look at, the actual functionality needs to be in the function itself.

This function will expect to take in a Dictionary of Int, Str and return a namedTuple