How to create a many-to-many relationship variable and increase code usability?












1















I'm trying to create a common utility for file transfer, from source to destination. The arguments are separated into dir and filename, which is the result of os.path.dirname(some_file) and os.path.basename(some_file), respectively. The destination filename is the same as the source filename by default if not specified.



I have created a script that at least is working perfectly well with the specific requirements in my first project. But as you can notice, the get_src_des method is very repetitive that I want to improve the code re-usability out from the nasty if...elif... statement. Anyone has better idea to rewrite this method?



class FileTransfer:

def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
self.ftp_dir = ftp_dir
self.ftp_filename = ftp_filename
self.local_dir = local_dir
self.local_filename = local_filename

self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
self.local_dict = self.get_group(local_dir, local_filename)

@staticmethod
def get_group(dir, filename):
group = {
"dir": dir,
"filename": filename,
}
return group

def get_src_des(self, src):
if src == "ftp":
dict_src = self.ftp_dict
dict_des = self.local_dict
elif src == "local":
dict_src = self.local_dict
dict_des = self.ftp_dict
else:
dict_src = None
dict_des = None

return dict_src, dict_des

# other methods, such as download_from_src_to_des, upload_from_src_to_des, ...









share|improve this question





























    1















    I'm trying to create a common utility for file transfer, from source to destination. The arguments are separated into dir and filename, which is the result of os.path.dirname(some_file) and os.path.basename(some_file), respectively. The destination filename is the same as the source filename by default if not specified.



    I have created a script that at least is working perfectly well with the specific requirements in my first project. But as you can notice, the get_src_des method is very repetitive that I want to improve the code re-usability out from the nasty if...elif... statement. Anyone has better idea to rewrite this method?



    class FileTransfer:

    def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
    self.ftp_dir = ftp_dir
    self.ftp_filename = ftp_filename
    self.local_dir = local_dir
    self.local_filename = local_filename

    self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
    self.local_dict = self.get_group(local_dir, local_filename)

    @staticmethod
    def get_group(dir, filename):
    group = {
    "dir": dir,
    "filename": filename,
    }
    return group

    def get_src_des(self, src):
    if src == "ftp":
    dict_src = self.ftp_dict
    dict_des = self.local_dict
    elif src == "local":
    dict_src = self.local_dict
    dict_des = self.ftp_dict
    else:
    dict_src = None
    dict_des = None

    return dict_src, dict_des

    # other methods, such as download_from_src_to_des, upload_from_src_to_des, ...









    share|improve this question



























      1












      1








      1








      I'm trying to create a common utility for file transfer, from source to destination. The arguments are separated into dir and filename, which is the result of os.path.dirname(some_file) and os.path.basename(some_file), respectively. The destination filename is the same as the source filename by default if not specified.



      I have created a script that at least is working perfectly well with the specific requirements in my first project. But as you can notice, the get_src_des method is very repetitive that I want to improve the code re-usability out from the nasty if...elif... statement. Anyone has better idea to rewrite this method?



      class FileTransfer:

      def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
      self.ftp_dir = ftp_dir
      self.ftp_filename = ftp_filename
      self.local_dir = local_dir
      self.local_filename = local_filename

      self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
      self.local_dict = self.get_group(local_dir, local_filename)

      @staticmethod
      def get_group(dir, filename):
      group = {
      "dir": dir,
      "filename": filename,
      }
      return group

      def get_src_des(self, src):
      if src == "ftp":
      dict_src = self.ftp_dict
      dict_des = self.local_dict
      elif src == "local":
      dict_src = self.local_dict
      dict_des = self.ftp_dict
      else:
      dict_src = None
      dict_des = None

      return dict_src, dict_des

      # other methods, such as download_from_src_to_des, upload_from_src_to_des, ...









      share|improve this question
















      I'm trying to create a common utility for file transfer, from source to destination. The arguments are separated into dir and filename, which is the result of os.path.dirname(some_file) and os.path.basename(some_file), respectively. The destination filename is the same as the source filename by default if not specified.



      I have created a script that at least is working perfectly well with the specific requirements in my first project. But as you can notice, the get_src_des method is very repetitive that I want to improve the code re-usability out from the nasty if...elif... statement. Anyone has better idea to rewrite this method?



      class FileTransfer:

      def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
      self.ftp_dir = ftp_dir
      self.ftp_filename = ftp_filename
      self.local_dir = local_dir
      self.local_filename = local_filename

      self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
      self.local_dict = self.get_group(local_dir, local_filename)

      @staticmethod
      def get_group(dir, filename):
      group = {
      "dir": dir,
      "filename": filename,
      }
      return group

      def get_src_des(self, src):
      if src == "ftp":
      dict_src = self.ftp_dict
      dict_des = self.local_dict
      elif src == "local":
      dict_src = self.local_dict
      dict_des = self.ftp_dict
      else:
      dict_src = None
      dict_des = None

      return dict_src, dict_des

      # other methods, such as download_from_src_to_des, upload_from_src_to_des, ...






      python






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 1 at 22:01









      martineau

      69k1091186




      69k1091186










      asked Jan 1 at 21:30









      D EmmaD Emma

      62




      62
























          2 Answers
          2






          active

          oldest

          votes


















          2














          Yes. This is classic use case for a dictionary.



          You can rewrite your code as follows:



          class FileTransfer:

          def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
          self.ftp_dir = ftp_dir
          self.ftp_filename = ftp_filename
          self.local_dir = local_dir
          self.local_filename = local_filename

          self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
          self.local_dict = self.get_group(local_dir, local_filename)
          self.param_dict = {
          'ftp':(self.ftp_dict,self.local_dict),
          'local' : (self.local_dict,self.ftp_dict)
          }

          @staticmethod
          def get_group(dir, filename):
          group = {
          "dir": dir,
          "filename": filename,
          }
          return group

          def get_src_des(self, src):
          if src in param_dict:
          return param_dict[src]

          else:
          return (None,None)


          Next time, instead of adding another elif statement, you just add another entry in your param_dict






          share|improve this answer

































            1














            I agree that that this could be done with a dictionary, as @Yakov Dan's answer suggests, but I would code it as shown below, which doesn't require any other changes to the class and is more dynamic.



            The get_group() method could be written more concisely, as indicated.



            class FileTransfer:
            ...

            @staticmethod
            def get_group(dir, filename):
            return dict(dir=dir, filename=filename)

            def get_src_des(self, src):
            return {
            'ftp': (self.ftp_dict, self.local_dict),
            'local': (self.local_dict, self.ftp_dict)
            }.get(src, (None, None))





            share|improve this answer


























            • This version of get_src_des creates the dict each time. Creating it once in __init__ is more efficient.

              – cco
              Jan 1 at 23:33











            • @cco: True, but creating it on-the-fly means that it uses the current values of the instance's attributes, not what they were when it was created. It also doesn't require modifying any other parts of the class—so unless doing it dynamically as show is causing a significant slow-down—so it sounds to me like your suggestion is a premature optimization.

              – martineau
              Jan 1 at 23:51













            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53999085%2fhow-to-create-a-many-to-many-relationship-variable-and-increase-code-usability%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            Yes. This is classic use case for a dictionary.



            You can rewrite your code as follows:



            class FileTransfer:

            def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
            self.ftp_dir = ftp_dir
            self.ftp_filename = ftp_filename
            self.local_dir = local_dir
            self.local_filename = local_filename

            self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
            self.local_dict = self.get_group(local_dir, local_filename)
            self.param_dict = {
            'ftp':(self.ftp_dict,self.local_dict),
            'local' : (self.local_dict,self.ftp_dict)
            }

            @staticmethod
            def get_group(dir, filename):
            group = {
            "dir": dir,
            "filename": filename,
            }
            return group

            def get_src_des(self, src):
            if src in param_dict:
            return param_dict[src]

            else:
            return (None,None)


            Next time, instead of adding another elif statement, you just add another entry in your param_dict






            share|improve this answer






























              2














              Yes. This is classic use case for a dictionary.



              You can rewrite your code as follows:



              class FileTransfer:

              def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
              self.ftp_dir = ftp_dir
              self.ftp_filename = ftp_filename
              self.local_dir = local_dir
              self.local_filename = local_filename

              self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
              self.local_dict = self.get_group(local_dir, local_filename)
              self.param_dict = {
              'ftp':(self.ftp_dict,self.local_dict),
              'local' : (self.local_dict,self.ftp_dict)
              }

              @staticmethod
              def get_group(dir, filename):
              group = {
              "dir": dir,
              "filename": filename,
              }
              return group

              def get_src_des(self, src):
              if src in param_dict:
              return param_dict[src]

              else:
              return (None,None)


              Next time, instead of adding another elif statement, you just add another entry in your param_dict






              share|improve this answer




























                2












                2








                2







                Yes. This is classic use case for a dictionary.



                You can rewrite your code as follows:



                class FileTransfer:

                def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
                self.ftp_dir = ftp_dir
                self.ftp_filename = ftp_filename
                self.local_dir = local_dir
                self.local_filename = local_filename

                self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
                self.local_dict = self.get_group(local_dir, local_filename)
                self.param_dict = {
                'ftp':(self.ftp_dict,self.local_dict),
                'local' : (self.local_dict,self.ftp_dict)
                }

                @staticmethod
                def get_group(dir, filename):
                group = {
                "dir": dir,
                "filename": filename,
                }
                return group

                def get_src_des(self, src):
                if src in param_dict:
                return param_dict[src]

                else:
                return (None,None)


                Next time, instead of adding another elif statement, you just add another entry in your param_dict






                share|improve this answer















                Yes. This is classic use case for a dictionary.



                You can rewrite your code as follows:



                class FileTransfer:

                def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
                self.ftp_dir = ftp_dir
                self.ftp_filename = ftp_filename
                self.local_dir = local_dir
                self.local_filename = local_filename

                self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
                self.local_dict = self.get_group(local_dir, local_filename)
                self.param_dict = {
                'ftp':(self.ftp_dict,self.local_dict),
                'local' : (self.local_dict,self.ftp_dict)
                }

                @staticmethod
                def get_group(dir, filename):
                group = {
                "dir": dir,
                "filename": filename,
                }
                return group

                def get_src_des(self, src):
                if src in param_dict:
                return param_dict[src]

                else:
                return (None,None)


                Next time, instead of adding another elif statement, you just add another entry in your param_dict







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 1 at 22:46









                Josué Cortina

                1,5861512




                1,5861512










                answered Jan 1 at 21:37









                Yakov DanYakov Dan

                1,401717




                1,401717

























                    1














                    I agree that that this could be done with a dictionary, as @Yakov Dan's answer suggests, but I would code it as shown below, which doesn't require any other changes to the class and is more dynamic.



                    The get_group() method could be written more concisely, as indicated.



                    class FileTransfer:
                    ...

                    @staticmethod
                    def get_group(dir, filename):
                    return dict(dir=dir, filename=filename)

                    def get_src_des(self, src):
                    return {
                    'ftp': (self.ftp_dict, self.local_dict),
                    'local': (self.local_dict, self.ftp_dict)
                    }.get(src, (None, None))





                    share|improve this answer


























                    • This version of get_src_des creates the dict each time. Creating it once in __init__ is more efficient.

                      – cco
                      Jan 1 at 23:33











                    • @cco: True, but creating it on-the-fly means that it uses the current values of the instance's attributes, not what they were when it was created. It also doesn't require modifying any other parts of the class—so unless doing it dynamically as show is causing a significant slow-down—so it sounds to me like your suggestion is a premature optimization.

                      – martineau
                      Jan 1 at 23:51


















                    1














                    I agree that that this could be done with a dictionary, as @Yakov Dan's answer suggests, but I would code it as shown below, which doesn't require any other changes to the class and is more dynamic.



                    The get_group() method could be written more concisely, as indicated.



                    class FileTransfer:
                    ...

                    @staticmethod
                    def get_group(dir, filename):
                    return dict(dir=dir, filename=filename)

                    def get_src_des(self, src):
                    return {
                    'ftp': (self.ftp_dict, self.local_dict),
                    'local': (self.local_dict, self.ftp_dict)
                    }.get(src, (None, None))





                    share|improve this answer


























                    • This version of get_src_des creates the dict each time. Creating it once in __init__ is more efficient.

                      – cco
                      Jan 1 at 23:33











                    • @cco: True, but creating it on-the-fly means that it uses the current values of the instance's attributes, not what they were when it was created. It also doesn't require modifying any other parts of the class—so unless doing it dynamically as show is causing a significant slow-down—so it sounds to me like your suggestion is a premature optimization.

                      – martineau
                      Jan 1 at 23:51
















                    1












                    1








                    1







                    I agree that that this could be done with a dictionary, as @Yakov Dan's answer suggests, but I would code it as shown below, which doesn't require any other changes to the class and is more dynamic.



                    The get_group() method could be written more concisely, as indicated.



                    class FileTransfer:
                    ...

                    @staticmethod
                    def get_group(dir, filename):
                    return dict(dir=dir, filename=filename)

                    def get_src_des(self, src):
                    return {
                    'ftp': (self.ftp_dict, self.local_dict),
                    'local': (self.local_dict, self.ftp_dict)
                    }.get(src, (None, None))





                    share|improve this answer















                    I agree that that this could be done with a dictionary, as @Yakov Dan's answer suggests, but I would code it as shown below, which doesn't require any other changes to the class and is more dynamic.



                    The get_group() method could be written more concisely, as indicated.



                    class FileTransfer:
                    ...

                    @staticmethod
                    def get_group(dir, filename):
                    return dict(dir=dir, filename=filename)

                    def get_src_des(self, src):
                    return {
                    'ftp': (self.ftp_dict, self.local_dict),
                    'local': (self.local_dict, self.ftp_dict)
                    }.get(src, (None, None))






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 1 at 22:32

























                    answered Jan 1 at 22:24









                    martineaumartineau

                    69k1091186




                    69k1091186













                    • This version of get_src_des creates the dict each time. Creating it once in __init__ is more efficient.

                      – cco
                      Jan 1 at 23:33











                    • @cco: True, but creating it on-the-fly means that it uses the current values of the instance's attributes, not what they were when it was created. It also doesn't require modifying any other parts of the class—so unless doing it dynamically as show is causing a significant slow-down—so it sounds to me like your suggestion is a premature optimization.

                      – martineau
                      Jan 1 at 23:51





















                    • This version of get_src_des creates the dict each time. Creating it once in __init__ is more efficient.

                      – cco
                      Jan 1 at 23:33











                    • @cco: True, but creating it on-the-fly means that it uses the current values of the instance's attributes, not what they were when it was created. It also doesn't require modifying any other parts of the class—so unless doing it dynamically as show is causing a significant slow-down—so it sounds to me like your suggestion is a premature optimization.

                      – martineau
                      Jan 1 at 23:51



















                    This version of get_src_des creates the dict each time. Creating it once in __init__ is more efficient.

                    – cco
                    Jan 1 at 23:33





                    This version of get_src_des creates the dict each time. Creating it once in __init__ is more efficient.

                    – cco
                    Jan 1 at 23:33













                    @cco: True, but creating it on-the-fly means that it uses the current values of the instance's attributes, not what they were when it was created. It also doesn't require modifying any other parts of the class—so unless doing it dynamically as show is causing a significant slow-down—so it sounds to me like your suggestion is a premature optimization.

                    – martineau
                    Jan 1 at 23:51







                    @cco: True, but creating it on-the-fly means that it uses the current values of the instance's attributes, not what they were when it was created. It also doesn't require modifying any other parts of the class—so unless doing it dynamically as show is causing a significant slow-down—so it sounds to me like your suggestion is a premature optimization.

                    – martineau
                    Jan 1 at 23:51




















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53999085%2fhow-to-create-a-many-to-many-relationship-variable-and-increase-code-usability%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                    How to fix TextFormField cause rebuild widget in Flutter