-2

I have a function that converts args given by argparse to a filename:

def args2filename(args, prefix):
    filename = prefix
    kwargs = vars(args)
    for key, value in sorted(kwargs.items()):
        filename += f'_{key}={value}'
    return filename

What is the Python convention for such functions? I'd guess it would be more appropriate to use args_to_filename (or maybe argstofilename as in 2to3) instead of args2filename, but I couldn't find a reference.

I've found this answer for Python, but it addresses the case when you have a class. @lvc suggests from_foo, if Bar.__init__ already takes a different signature:

 class Bar:
      @classmethod
      def from_foo(cls, f):
          '''Create a new Bar from the given Foo'''
          ret = cls()
          # ...

So, I'm looking for a Pythonic answer in these two cases, i.e., when I don't necessarily need a class, and when I have one.

2

The PEP-8 style guide suggests using lowercase with underscores for function names. Incidentally, this style is also known as snake_case. Coincidence, or irony? :)

So if you wish to follow those conventions, then args_to_filename is a good choice. Of course, such guidelines are just that: a guide. As long as you are consistent with your own convention, then you are free to disregard "official" guidelines in favour of your own. Consistency is the key. Following a convention is just an easy way of achieving that consistency.

Regarding when to have a free function and when to have a method in a class, that's largely a matter of preference. The rule of thumb I use (for any language; not just Python) is:

Is the function "pure", ie is it deterministic (the same input arguments always yield the same result) and has no side effects (it doesn't read/write to external resources, eg global variables, environment variable or the file system)?
- If yes, make it a free function.
- If no, make it a method in a class

But others will have other criteria for deciding which option to pick.

| improve this answer | |
-1

I think it could be better to use it in a generic form so you convert some args to a specific format. simply say toYourFormat in your case you can keep on saying toFileName but if you found a more generic name it can be better.

But anyway I think your design could be better if these args was instead a class that toFileName is a method of it and the class is responsible of collecting the args and converting them. it's just a thought so it is not necessary the right one

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.