This question has been flagged
3 Replies
51 Views

I need to know what is the difference between private functions and public functions in odoo python with example, and the usage.

Avatar
Discard
Best Answer

Hi,

1)Public Functions  in Odoo

Public functions in Odoo classes (which typically represent Odoo models) are denoted by the absence of a leading underscore (_) in their names.These functions can be called directly from Odoo's user interface (UI) elements like buttons, menus, or workflows, as well as from other Python code within your custom Odoo modules.

Example:

class SaleOrder(models.Model):

    _name = 'sale.order'


    def confirm_sale(self):

        # Public function to confirm a sale order

        # This function can be called from buttons or workflows

        # ... (implementation logic)

2)Private Functions in Odoo


Private functions in Odoo are identified by a leading underscore (_) in their names.

While technically accessible from anywhere in your code, private functions are generally intended for internal use within the class. They're not directly callable from the Odoo UI or other modules.

Example:


class SaleOrder(models.Model):

    _name = 'sale.order'


    def _check_stock_availability(self):

        # Private function to check stock availability before confirming a sale

        # This function is used internally by the confirm_sale method

        # ... (implementation logic)


    def confirm_sale(self):

        if self._check_stock_availability():

            # Logic to confirm sale if stock is available

            # ...

        else:

            # Handle insufficient stock scenario

            # ...


Hope it helps

Avatar
Discard
Best Answer

From https://www.odoo.com/documentation/17.0/developer/reference/backend/security.html#unsafe-public-methods

Unsafe Public Methods

Any public method can be executed via a RPC call with the chosen parameters. The methods starting with a _ are not callable from an action button or external API.

On public methods, the record on which a method is executed and the parameters can not be trusted, ACL being only verified during CRUD operations.

# this method is public and its arguments can not be trusted
def action_done(self):
    if self.state == "draft" and self.user_has_groups('base.manager'):
        self._set_state("done")

# this method is private and can only be called from other python methods
def _set_state(self, new_state):
    self.sudo().write({"state": new_state})

Making a method private is obviously not enough and care must be taken to use it properly.


Avatar
Discard
Best Answer

class TestClass:

    def PublicFunc(self):

        print("This is a public function")

        self.__Privatefunc() # this is good practice


    def _Privatefunc(self):

        print("This is a private function")


o = MyClass()

o.Publicfunc()  

o._PrivateFunc()  #This is bad practice

Avatar
Discard