__init__, __slot__ and **keywordargs

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Zunbeltz Izaola

    __init__, __slot__ and **keywordargs


    Hi,

    I'm playing with __slot__ (new class) and the __init__ method of my
    class. I want the arguments of __init__ to be keywords and that the
    method initialize all the attributes in __slot__ to None except those
    in the argument of __init__ (Is this a good practice?). I've the
    following class

    class PersonalData(ob ject):

    __slot__ = ("Firstname" , # Firstname of the person.
    "Surname", # Surname of the person.
    "Birthdate" , # Birthdate of the person.
    "Nationalit y" # Nationality of the person.
    )

    def __init__(self,* *args):
    for kwrd, value in args.items():
    self.__setattr_ _(kwrd,args[kwrd]

    # for arg,value in args.items():
    # if arg in self.__slot__:
    # self.__setattr_ _(arg,value)
    # else:
    # errmsg = str(self.__clas s__.__name__)
    # errmsg += "object has not attribute " + arg
    # raise AttributeError, errmsg

    def __str__(self):
    buffer = ""
    for attr in self.__slot__:
    if attr in self.__dict__.k eys():
    buffer += attr + ": " + str(self.__geta ttribute__(attr )) + "\n"

    The problem is that the __init__ defined can set attributes that are
    not in the slot and i want to have an exception when someone tries to
    do

    inst = PersonalData(no attribute = "Smith")

    I've coded the solution in the fragment that is commented, raising and
    exception manually. Someone knows a more elegant solution and can
    explain with the first definition didn't raise and exception?

    Thanks in advance

    Zunbeltz
    --
    Remove XXX from email: zunbeltz@wm.lc. ehu.esXXX
  • Peter Otten

    #2
    Re: __init__, __slot__ and **keywordargs

    Zunbeltz Izaola wrote:
    [color=blue]
    > I'm playing with __slot__ (new class) and the __init__ method of my
    > class. I want the arguments of __init__ to be keywords and that the
    > method initialize all the attributes in __slot__ to None except those
    > in the argument of __init__ (Is this a good practice?). I've the
    > following class[/color]

    You misspelt: in fact it's __slots__, and it will work as expected. As far
    as I know slots are an optimization technique that is useful to save some
    space, when you have many (that would be millions) of small objects. It's
    not meant as a safety belt for the programmer.
    In your case, I wouldn't use it, but rather not initialize the attributes
    not given as constructor - __init__() - arguments. Also, I would consider
    the ability to provide additional arguments, say "Nickname", not a bug but
    a feature. Of course you have to change your client code to test for

    hasattr(person, "Birthday")

    instead of

    person.Birthday is None

    Peter


    Comment

    • Zunbeltz Izaola

      #3
      Re: __init__, __slot__ and **keywordargs

      Peter Otten <__peter__@web. de> writes:
      [color=blue]
      >
      > You misspelt: in fact it's __slots__, and it will work as expected. As far[/color]

      Hurg!!! :-( This kine of mistakes will become me crazy.
      [color=blue]
      > as I know slots are an optimization technique that is useful to save some
      > space, when you have many (that would be millions) of small objects. It's
      > not meant as a safety belt for the programmer.[/color]

      But, I think it can be considered "a safety belt for the programmer" ,
      When you do

      instance.attrib ute

      you get and AttributeError if attribute is not in the __slots__
      (It would help to avoid misspells, like i've done!!)
      [color=blue]
      > In your case, I wouldn't use it, but rather not initialize the attributes
      > not given as constructor - __init__() - arguments. Also, I would consider
      > the ability to provide additional arguments, say "Nickname", not a
      > bug but[/color]

      What do you mean with additional arguments? (My code was not the full
      code)
      [color=blue]
      > a feature. Of course you have to change your client code to test for
      >[/color]

      Not yet :-) I'm in planning stage yet and this code was only to play a
      bit to see what can i do.
      [color=blue]
      > hasattr(person, "Birthday")
      >
      > instead of
      >
      > person.Birthday is None
      >[/color]

      Thanks for this suggestion, I think i'll use hasattr.

      Zunbeltz
      [color=blue]
      > Peter
      >
      >[/color]

      --
      Remove XXX from email: zunbeltz@wm.lc. ehu.esXXX

      Comment

      • Peter Otten

        #4
        Re: __init__, __slot__ and **keywordargs

        Zunbeltz Izaola wrote:
        [color=blue]
        > Peter Otten <__peter__@web. de> writes:
        >[color=green]
        >>
        >> You misspelt: in fact it's __slots__, and it will work as expected. As
        >> far[/color]
        >
        > Hurg!!! :-( This kine of mistakes will become me crazy.
        >[color=green]
        >> as I know slots are an optimization technique that is useful to save some
        >> space, when you have many (that would be millions) of small objects. It's
        >> not meant as a safety belt for the programmer.[/color]
        >
        > But, I think it can be considered "a safety belt for the programmer" ,
        > When you do[/color]

        It can, but I think it's contrary to the Python style, which relies heavily
        on unit tests. If you to want ensure a limited set of attributes, then why
        would you allow both an integer and a Date for the Birthday - if you follow
        this road, you end up programming in Java, because it's designed for that
        kind of safety. Most Pythonistas think that you are spending too much time
        on errors that comprise only a small fraction of what goes wrong in real
        programs.
        [color=blue]
        > instance.attrib ute
        >
        > you get and AttributeError if attribute is not in the __slots__
        > (It would help to avoid misspells, like i've done!!)[/color]

        Note that you already get an AttributeError for read access. Write access
        aka rebinding is used only in a fraction of all accesses and prohibiting it
        for arbitrary attribute names IMHO significantly impairs the usefulness of
        Python's object model.
        [color=blue][color=green]
        >> In your case, I wouldn't use it, but rather not initialize the attributes
        >> not given as constructor - __init__() - arguments. Also, I would consider
        >> the ability to provide additional arguments, say "Nickname", not a
        >> bug but[/color]
        >
        > What do you mean with additional arguments? (My code was not the full
        > code)[/color]

        Let's assume you have mandatory arguments Firstname and Surname but want to
        allow for other information. A constructor reflecting that would then be

        def __init__(self, Firstname, Surname, **OptionalAttri butes)

        It's up to the clientcode to decide what these optional attributes may be,
        so they could vary in different contexts. This in turn makes your class
        useful for a broader range of usecases.

        Peter

        Comment

        Working...