0

code style 1:

from ..service.user_service import UserService

class UserView:
    user_service = UserService()
    user_service.get_all_users()
    # rest of code

code style 2:

from ..service.user_service import UserService as userService

class UserView:
    userService.get_all_users()
    # rest of code

service.user_service.py

from .models.user import User # please 
class UserService:
    def get_all_users(self):
        return User.objects.all()

both code works fine but which is the proper way? And also I want to know if this things may cause of the circular import error?. I have went through this question Circular (or cyclic) imports in Python.

And what is the working mechanism of style 2 code?

R.A.Munna
  • 1,699
  • 1
  • 15
  • 29
  • Neither of these are right. UserService should not exist. But the question is very confusing, why would you think that importing a class with a lower-case name would make it an instance? Why would you think that would help with circular imports? – Daniel Roseman Mar 12 '19 at 11:57
  • @DanielRoseman I have imported both way in `UserView` class that's why I have asked for? I thought its instance due to I have performed operation like instance. If I am wrong or my thinking is wrong please guide me the correct way. That's why I ask – R.A.Munna Mar 12 '19 at 12:07
  • 1
    But this is not real code. Changing the name of an import does not make a class an instance. This code does not work. And anyway, as I say, in Django you don't write classes like UserService; the User class and its Manager already give you the encapsulation you need. Python is not Java. – Daniel Roseman Mar 12 '19 at 12:20
  • @DanielRoseman I think you right but unfortunately I have done it like java. this is real I mean everything are working as well as other api's also implement like this way. Any way thank you I will keep in mind if possible for current but sure in next time project creation. – R.A.Munna Mar 12 '19 at 12:28
  • @DanielRoseman you are right if we are talking about relatively small projects. The funny UserService in this question is not a good example for what I'm trying to say. But once you work on something really big, you can end up with model classes, where many of them are even 10000 lines of code long and depends on dozens of other models. I've encountered this when I joined one of the projects. Believe or not but introducing additional layer between views and models can help organizing code and making the project maintainable again. – ElmoVanKielmo Mar 14 '19 at 06:35
  • @ElmoVanKielmo exactly I am facing it and try to implement like as you explain. Though, the way is not the pythonic way, I am trying. – R.A.Munna Mar 14 '19 at 09:17

0 Answers0