Home > other >  How can i make a method available only from within the class
How can i make a method available only from within the class

Time:12-24

Good evening, i need an advice, googling i couldn't find a proper direction. I need to make a method available only within the class (i.e other methods or functions), if called from the program as a method of the object referring to the class i want:

  • the method to be invisible/not available to the intellisense
  • if i'm stubborn, and code it anyway, must raise an error.

Attaching a screenshot to make it more clear. Any advice is appreciated, Thank you.

Screenshot of the problem

CodePudding user response:

There's no private methods in python. Common usage dictates to precede a method that's only supposed to be used internally with one or two underscores, depending on the case. See here: What is the meaning of single and double underscore before an object name?

CodePudding user response:

As others have mentioned there are no private methods in Python. I also don't know how to make it invisible for intelisense (probably there is some setting), but what you could theoretically do is this:

import re


def make_private(func):
    def inner(*args, **kwargs):
        name = func.__name__
        pattern = re.compile(fr'(.*)\.{name}')
        with open(__file__) as file:
            for line in file:
                lst = pattern.findall(line)
                if (lst and not line.strip().startswith('#')
                   and not all(g.strip() == 'self' for g in lst)):
                    raise Exception()
        return func(*args, **kwargs)
    return inner


class MyClass:

    @make_private
    def some_method(self):
        pass

    def some_other_method(self):
        self.some_method()


m = MyClass()
# m.some_method()
m.some_other_method()

It (make_private) is a decorator which basically when you call the function it is decorating, it first reads the entire file line by line and tries to find if in all of the file this method is called without being prefixed with self.. So if it is not then it is considered to be called from outside the class and an Exception is raised (probably add some message to it tho).

Issues could start once you have multiple files and this wouldn't entirely prevent someone from calling it if they really wanted for example if they did it like this:

self = MyClass()
self.some_method()

But mostly this would raise an exception.

CodePudding user response:

OK Solved, to hide the method to the ide's Intellisense i added the double underscore (works fine with pycharm, not with vscode) then i used the accessify module to prevent forced execution calling myobj._myclass__somemethod()

from accessify import private

class myclass:
    @private
    def __somemethod(self)
  • Related