Advanced Usage Patterns
class PrivacyMetaclass(type):
def __new__(cls, name, bases, attrs):
private_attrs = {}
for key, value in attrs.items():
if key.startswith('__') and not key.endswith('__'):
private_attrs[f'_{name}{key}'] = value
del attrs[key]
attrs.update(private_attrs)
return super().__new__(cls, name, bases, attrs)
class SecureModel(metaclass=PrivacyMetaclass):
def __init__(self):
self.__secret_data = "Confidential Information"
Privacy Flow Visualization
graph TD
A[Class Definition] --> B{Privacy Level}
B -->|Weak Privacy| C[Single Underscore]
B -->|Strong Privacy| D[Double Underscore]
B -->|Advanced Control| E[Metaclass]
C --> F[Naming Convention]
D --> G[Name Mangling]
E --> H[Dynamic Attribute Management]
Decorator-Based Privacy Enforcement
def private_method(func):
def wrapper(self, *args, **kwargs):
if not hasattr(self, '_authorized'):
raise PermissionError("Unauthorized access")
return func(self, *args, **kwargs)
return wrapper
class SecureSystem:
def __init__(self):
self._authorized = False
@private_method
def sensitive_operation(self):
print("Executing sensitive operation")
Privacy Patterns Comparison
Pattern |
Complexity |
Use Case |
Protection Level |
Single Underscore |
Low |
Hint of Internal Use |
Weak |
Double Underscore |
Medium |
Name Mangling |
Strong |
Metaclass |
High |
Dynamic Privacy Control |
Advanced |
Decorator |
Medium |
Access Validation |
Conditional |
Dynamic Privacy Management
class FlexiblePrivacyManager:
def __init__(self):
self.__private_store = {}
self.__access_levels = {}
def set_private_attr(self, name, value, access_level=0):
self.__private_store[name] = value
self.__access_levels[name] = access_level
def get_private_attr(self, name, current_level=0):
if name in self.__private_store:
if current_level >= self.__access_levels.get(name, 0):
return self.__private_store[name]
raise PermissionError("Insufficient access level")
Context-Aware Privacy Mechanism
class ContextualPrivacy:
def __init__(self):
self.__sensitive_data = {}
def __enter__(self):
## Setup secure context
return self
def __exit__(self, exc_type, exc_val, exc_tb):
## Clear sensitive data
self.__sensitive_data.clear()
def store_sensitive_info(self, key, value):
self.__sensitive_data[key] = value
LabEx Privacy Best Practices
At LabEx, we recommend a multi-layered approach to privacy:
- Use naming conventions as primary indicators
- Implement additional access controls when necessary
- Balance between flexibility and security
- Document privacy expectations clearly
Advanced Error Handling
class StrictPrivacyEnforcer:
def __init__(self):
self.__critical_data = {}
def __setattr__(self, name, value):
if name.startswith('__') and not name.endswith('__'):
if hasattr(self, name):
raise AttributeError("Cannot modify private attributes")
super().__setattr__(name, value)