0

I am trying to write Python 2.7 cod that is easier to scale by removing argument order while providing default values in the case that requirements change. Here is my code:

# Class:
class Mailer(object):
    def __init__(self, **args):
        self.subject=args.get('subject', None)
        self.mailing_list=args.get('mailing_list', None)
        self.from_address=args.get('from_address', None)
        self.password=args.get('password', None)
        self.sector=args.get('sector', "There is a problem with the HTML")
# call: 
mailer=Mailer(
    subject="Subject goes here", 
    password="password",
    mailing_list=("email@email.com", "email@email.com","email@email.com"),
    mailing_list=("email@email.com", "email@email.com"),
    from_address="email@email.com",
    sector=Sector()

)

I'm still new to the language so if there is a better way to achieve this, I'd really like to know. Thanks in advance.

marco_c
  • 1
  • 2

2 Answers2

0

Try this way of initialize your class:

class Mailer(object):
    def __init__(self, **args):
        for k in args:
            self.__dict__[k] = args[k]
xbb
  • 2,073
  • 1
  • 19
  • 34
0

The problem with the way you're doing it is that there is no documentation about what arguments the class accepts, so help(Mailer) is useless. What you should do is provide default argument values in the __init__() method where possible.

To set the arguments as attributes on the instance, you can use a little introspection, as in another answer I wrote, to avoid all the boilerplace self.foo = foo stuff.

class Mailer(object):
    def __init__(self, subject="None", mailing_list=(),
                 from_address="noreply@example.com", password="hunter42",
                 sector="There is a problem with the HTML"):

    # set all arguments as attributes of this instance
    code     = self.__init__.__func__.func_code
    argnames = code.co_varnames[1:code.co_argcount]
    locs     = locals()
    self.__dict__.update((name, locs[name]) for name in argnames)

You can provide the arguments in any order if you make the call using explicit argument names, regardless of how they're defined in the method, so your example call will still work.

Community
  • 1
  • 1
kindall
  • 178,883
  • 35
  • 278
  • 309